简短答案
$model->relation()返回 关系对象
$model->relation返回关系的 结果
长答案
$model->relation()可以解释得很简单。您正在调用定义关系的实际函数。您的for
distributor可能看起来像这样:
public function distributors(){ return $this->hasMany('Distributor');}因此,在调用时,
$store->distributors()您仅获得其返回值
$this->hasMany('Distributor')是的一个实例IlluminateDatabaseEloquentRelationsHasMany
什么时候使用?
如果要在运行查询之前进一步指定查询,通常会调用关系函数。例如,添加一个where语句:
$distributors = $store->distributors()->where('priority', '>', 4)->get();当然,您也可以这样做:
$store->distributors()->get()但这与的结果相同
$store->distributors。
这使我对 动态关系属性 进行了解释。
Laravel在幕后做了一些事情,使您可以直接访问关系的结果作为属性。像:
$model->relation。
这是发生在
IlluminateDatabaseEloquentModel
1) 这些属性实际上不存在。因此,如果您访问
$store->distributors该电话,它将被代理到
__get()
2) 然后此方法
getAttribute使用属性名称进行调用
getAttribute('distributors')public function __get($key){ return $this->getAttribute($key);}3)
在
getAttribute其中检查该关系是否已经加载(存在于中
relations)。如果不存在并且存在关系方法,它将加载关系(
getRelationshipFromMethod)
public function getAttribute($key){ // pre 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()查询生成器实例上产生a
。(结果与相同
$model->relation()->get()。



