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

How does laravel model relationships work in core?

考虑这个例子

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

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

基本上,每当您尝试从模型访问 属性 时,都会调用 __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 是否是 属性模型或者如果它是模型本身中定义的访问器方法,那么它只是 returns 属性 否则它会继续进一步检查,如果它找到模型中使用该名称定义的方法(属性 /$kay) 那么它就是简单的returns关系。