我无法使用 Laravel 进行查询

I can not make a query with Laravel

早上好,我在尝试使用 Eloquent 创建简单查询时遇到了问题。

这是 mi colonia 模型:

class Colonia extends Model
{
    protected $table = 'catalogo_colonias';   

    public function city()
    {
        return $this->belongsTo('App\City', 'ciudades_id');
    }
}

如果我愿意。

$response = Colonia::find(1)->city;

我正在收到回复,但我不想通过 ID 查找,我正在尝试做这样的事情。

$response = Colonia::where('codigo_postal', $codigo_postal)->city;

但它抛出一个错误。

Undefined property: Illuminate\Database\Eloquent\Builder::$city

如你所见,上面声明了,我猜这是一个语法问题,希望你能帮助我。

谢谢你,问候。

当你这样做时:

$response = Colonia::find(1)->city;

find() 方法将return 查询结果,在本例中是catalogo_colonias table 的第一个对象。单个对象,此对象具有您定义的所有属性,例如 city 关系。

现在,当你使用where() method instead, this still hasn't retrieve the relationship objects yet because in some cases you would want to keep constraining the query. Instead, it returns an instance of the Query Builderclass。这就是它抛出错误的原因:

$response = Colonia::where('codigo_postal', $codigo_postal) // return query builder
                 ->city; // this property isn't defined in the builder, hence, the error.

要获得结果,您需要附加 get()(以获得与查询匹配的所有结果)或 first()

$response = Colonia::where('codigo_postal', $codigo_postal) // query builder
                 ->first() // returns an instance of Colonia
                 ->city; // now it can access the model properties.

您的代码中的问题是 Colonia::where() returns 查询生成器。你需要提取它,使用方法first(),如:

$response = Colonia::where('codigo_postal', $codigo_postal)->first()->city;

您可以使用两种方法从查询中提取信息:first()get()first() returns 只找到第一个元素,get() returns 一个包含整个结果的数组。

我建议你阅读 Laravel Query Builder - Where Clauses

别担心。这很容易修复。您已指定要搜索的列。但是 Eloquent 并没有真正执行您的查询。

如果您使用 Model::where('col', $value'),您必须指定:

  1. 你想要return一个模特行吗?如果是这样,您可以使用 first() p.s。它会 return 它找到的第一个,所以如果你试图找到 Bob 的名字,并且你有记录 Bob1, Bob2, Bob3 它会 return Bob1 第一个。

  2. 您想 return 查询中的所有行,您可以使用 get()。您必须 foreach 您的 collection 才能访问每个实例的关系。

然后您可以访问您的关系属性。

祝你好运!

根据@HCK的回答已经解释了如何执行查询结果。这里我只是想改进直接return列值的方法。

$response = Colonia::where('codigo_postal', $codigo_postal)
    ->value('city');

Laravel Documentation