栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

方法调用之间的区别$ model-> relation(); 和$ model-> relation;

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

方法调用之间的区别$ model-> relation(); 和$ model-> relation;

简短答案

$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()



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/440263.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号