laravel - Laravel 模型关系如何在核心中工作?

标签 laravel function oop relationships brackets

考虑这个例子

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/

相关文章:

php - Laravel 以干净的方式排除资源丰富的功能

php - 我可以测试回调是否有效吗?

c# - 如何向工厂模式添加新的派生类型?

php - 将变量与实例传递给构造函数

javascript - Laravel:注册表单打开时 session 过期

php - 如何使用 Laravel http post 禁用 SSL 检查

php - 在 laravel blade 中查找 foreach 循环的最后一次迭代

c++ - 将函数的数组地址返回到指针 (C++)

php - php用小数据生成不同的钟形曲线

c++ - C++ 中的新建、删除和子类