laravel模型关系如何在核心中发挥作用?

Gio*_*dze 2 oop brackets function relationships laravel

考虑这个例子

class SomeClass extends Model{
    public function user(){
        return $this->belongsTo('App\User');
    }
}
$instance = SomeClass::findOrFail(1);
$user = $instance->user;
Run Code Online (Sandbox Code Playgroud)

laravel怎么知道(我的意思是核心)$ instance-> user(没有括号)返回相关的模型?

The*_*pha 5

基本上,每当您尝试从模型访问属性时,都会调用__get 魔术方法,它类似于以下内容:

public function __get($key)
{
    return $this->getAttribute($key);
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,__getmagic方法调用另一个用户定义的方法(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);
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下(对于关系),最后一行return $this->getRelationValue($key);负责检索关系.继续阅读源代码,跟踪每个函数调用,你就会明白.从Illuminate\Database\Eloquent\Model.php::__get方法开始.顺便说一句,这段代码取自最新版本,Laravel但最终过程是一样的.

简短摘要:Laravel首先检查属性/ $kay被访问的属性是否是模型的属性,或者它是否是模型本身定义的访问器方法,然后它只返回该属性,否则它会继续进一步检查,如果它找到了在使用该名称(property/$kay)的模型然后它只返回关系.