Laravel 5 Laravel是否缓存多态调用?

Laravel 5 Laravel是否缓存多态调用?,laravel-5,eloquent,laravel-5.2,Laravel 5,Eloquent,Laravel 5.2,得到了这样的多态关系:用户->变形->来自不同平台的订阅。玩具但工作示例: class Polymorph { ... public function user() { return $this->belongsTo(User::class); } public function subscription() { return $this->morphTo(); } public fu

得到了这样的多态关系:用户->变形->来自不同平台的订阅。玩具但工作示例:

class Polymorph
{
    ...
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function subscription()
    {
        return $this->morphTo();
    }

    public function isExpired()
    {
        return $this->subscription->isExpired(); // Checks an attribute
    }

    public function isActive()
    {
        return $this->subscription->isActive(); // Checks an attribute
    }
    ...
}

class User{
    ...
    public function poly()
    {
        return $this->hasOne(Polymorph::class);
    }
    ...
}
我正在做:

$poly = $user->poly
$poly->isExpired(); // One DB call
$poly->isActive(); // No DB call
// etc..
似乎Laravel缓存了$this->subscription调用。在调用这些方法时,我会查看查询日志,对于适当的订阅对象,只有一个SELECT


我看了所有的文件,但我想我没有发现任何关于它的东西。它正在被缓存吗?如果是的话,它叫什么?或者有描述它的文档吗?

对你的问题的简短回答是肯定的。加载所有关系后,Laravel会缓存这些关系的结果,这样关系查询就不需要多次运行

你可以从源头上寻找


我想你说的是拉威尔5.2。如您所见,关系结果缓存在模型的$this->relations成员中。

@Kaspars是一个糟糕的例子。将替换它。Laravel使用特定类的对象创建这些属性。一旦创建,它就不需要重新创建和重新填充。访问该属性两次不会再次运行查询来填充它。@Phiter有道理。看来我需要深入研究并了解其机理。只是想在我之前确定一下。
public function getRelationValue($key)
{
    // If the key already exists in the relationships array, it just means the
    // relationship has already been loaded, so we'll just return it out of
    // here because there is no need to query within the relations twice.
    if ($this->relationLoaded($key)) {
        return $this->relations[$key];
    }
    // If the "attribute" exists as a method on the model, we will just assume
    // it is a relationship and will load and return results from the query
    // and hydrate the relationship's value on the "relationships" array.
    if (method_exists($this, $key)) {
        return $this->getRelationshipFromMethod($key);
    }
}