考虑这个例子
class SomeClass extends Model{
public function user(){
return $this->belongsTo('App\User');
}
}
$instance = SomeClass::findOrFail(1);
$user = $instance->user;
laravel 如何知道(我的意思是核心)$instance->user(不带括号)返回相关模型?
最佳答案
基本上,每当您尝试从模型访问属性时,__get
magic method被调用,它类似于以下内容:
public function __get($key)
{
return $this->getAttribute($key);
}
如您所见,__get
魔术方法调用另一个用户定义的方法 (getAttribute
),如下所示:
public function getAttribute($key)
{
if (! $key) {
return;
}
// If the attribute exists in the attribute array or has a "get" mutator we will
// get the attribute's value. Otherwise, we will proceed as if the developers
// are asking for a relationship's value. This covers both types of values.
if (array_key_exists($key, $this->attributes) ||
$this->hasGetMutator($key)) {
return $this->getAttributeValue($key);
}
// Here we will determine if the model base class itself contains this given key
// since we do not want to treat any of those methods are relationships since
// they are all intended as helper methods and none of these are relations.
if (method_exists(self::class, $key)) {
return;
}
return $this->getRelationValue($key);
}
在这种情况下(对于关系),最后一行 return $this->getRelationValue($key);
负责检索关系。继续阅读源代码,跟踪每个函数调用,您就会明白这一点。从 Illuminate\Database\Eloquent\Model.php::__get
方法开始。顺便说一句,此代码取自最新版本的 Laravel
,但最终过程是相同的。
简短总结:Laravel 首先检查正在访问的属性/$kay
是否是模型的属性,或者它是否是模型本身定义的访问器方法然后它只是返回该属性,否则它会继续进一步检查,如果它发现模型中使用该名称 (property/$kay
) 定义的方法,那么它只会返回关系。
关于laravel - Laravel 模型关系如何在核心中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44976115/