【问题标题】:How does laravel model relationships work in core?laravel 模型关系如何在核心工作?
【发布时间】:2017-12-12 01:36:34
【问题描述】:

考虑这个例子

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

laravel 如何知道(我的意思是核心) $instance->user(不带括号)返回相关模型?

【问题讨论】:

标签: laravel function oop relationships brackets


【解决方案1】:

基本上,每当您尝试从模型访问属性时,都会调用 __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) 在模型中定义的方法,那么它只会返回关系。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-11
    • 1970-01-01
    • 2020-03-09
    • 2012-04-22
    • 1970-01-01
    相关资源
    最近更新 更多