Laravel 是否缓存多态调用?

Does Laravel cache polymorphic calls?

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

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 缓存所有关系的结果,一旦它们被加载,这样关系查询就不需要 运行 多次。

你可以看看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 成员中。