这里我缺少一些基本的理解/理论。我不明白这些函数调用之间的区别:
$distributors = $store->distributors();
$distributors = $store->distributors;
$distributors = $store->distributors()->get();
$distributors = $store->distributors->get();
我在这里试图完成的是获取一家商店的分销商列表(多对多关系),然后他们将啤酒的每个分销商列表放入一个巨大的列表中。
foreach ($distributors as $distributor)
{
$available_beers = array_merge($distributor->beers(), $available_beers);
}
我不知道这是否是最好的方法,而且我无法让它工作。类似于第一个方法列表,不知道是需要->$beers
还是->$beers()
更新
感谢所有回答的人!这对我以后的工作有很好的引用作用。我最大的教训是取回集合与取回查询构建器/关系对象之间的区别。为了将来找到这个问题的人引用,这是我在我的 Controller 中设置的:
$store = $this->store->find($id)->first();
$distributors = $store->distributors;
$beers = [];
foreach ($distributors as $distributor){
$beers = array_merge($distributor->beers->lists('name', 'id'), $beers);
}
最佳答案
简答
$model->relation()
返回关系对象
$model->relation
返回关系的结果
长答案
$model->relation()
可以解释的很简单。您正在调用您定义关系的实际函数。您的 distributor
可能看起来像这样:
public function distributors(){
return $this->hasMany('Distributor');
}
因此,当调用 $store->distributors()
时,您只会得到 $this->hasMany('Distributor')
的返回值,它是 Illuminate\Database\Eloquent\Relations\HasMany
你什么时候使用它?
如果您想在运行之前进一步指定查询,通常会调用关系函数。例如添加一个 where 语句:
$distributors = $store->distributors()->where('priority', '>', 4)->get();
当然你也可以这样做:$store->distributors()->get()
但是这和 $store->distributors
有相同的结果.
这让我想到了动态关系属性的解释。
Laravel 在幕后做了一些事情,让您可以直接访问关系的结果作为属性。比如:$model->relation
。
这是 Illuminate\Database\Eloquent\Model
中发生的事情
1) 这些属性实际上并不存在。因此,如果您访问 $store->distributors
,调用将被代理到 __get()
2) 然后,此方法使用属性名称 getAttribute('distributors')
getAttribute
public function __get($key)
{
return $this->getAttribute($key);
}
3) 在 getAttribute
中,它检查关系是否已经加载(存在于 relations
中)。如果不存在并且存在关系方法,它将加载关系 (getRelationshipFromMethod
)
public function getAttribute($key)
{
// code omitted for brevity
if (array_key_exists($key, $this->relations))
{
return $this->relations[$key];
}
$camelKey = camel_case($key);
if (method_exists($this, $camelKey))
{
return $this->getRelationshipFromMethod($key, $camelKey);
}
}
4) 最后,Laravel 在关系上调用 getResults()
,然后在查询构建器实例上产生 get()
. (这给出了与 $model->relation()->get()
相同的结果。
关于php - 方法调用之间的区别 $model->relation();和 $model-> 关系;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28223289/