Laravel是否缓存多态调用?

时间:2018-08-29 14:23:16

标签: laravel-5 eloquent laravel-5.2

具有这样的多态关系:用户->多态->来自各种平台的订阅。玩具但可行的例子:

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

我浏览了文档,但认为没有发现任何相关信息。是否正在缓存?如果是这样,它叫什么名字?或者有描述它的文件?

1 个答案:

答案 0 :(得分:1)

您问题的简短答案是。一旦加载所有关系,Laravel会缓存所有关系的结果,这样就不必多次运行关系查询。

您可以查看GitHub的来源。

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);
    }
}

我假设您正在谈论Laravel 5.2。如您所见,关系结果缓存在模型的$this->relations成员中。