缓存 Eloquent 关系查询

Foo*_*Bar 7 php laravel eloquent laravel-5

我如何缓存这个 Eloquent 查询:

dd($user->roles);
Run Code Online (Sandbox Code Playgroud)

因为上面会以某种方式触发$user->roles()我假设的查询。

我试过这个:

    public function roles() {
        return \Cache::remember('user_' . $this->id . '_roles', 10, function() {
            return $this->hasMany('App\Role');
        });
    }
Run Code Online (Sandbox Code Playgroud)

但它不起作用,因为它必须返回一个数组,而不是雄辩的查询。

有什么建议?

Min*_*vME 14

这是我的方法:

public function bookmarks(): HasMany
{
    return $this->hasMany(Bookmark::class);
}

protected function getBookmarksCacheKey(): string
{
    return sprintf('user-%d-bookmarks', $this->id);
}

public function clearBookmarksCache(): bool
{
    return Cache::forget($this->getBookmarksCacheKey());
}

public function getBookmarksAttribute(): Collection
{
    if ($this->relationLoaded('bookmarks')) {
        return $this->getRelationValue('bookmarks');
    }

    $bookmarks = Cache::rememberForever($this->getBookmarksCacheKey(), function () {
        return $this->getRelationValue('bookmarks');
    });

    $this->setRelation('bookmarks', $bookmarks);

    return $bookmarks;
}
Run Code Online (Sandbox Code Playgroud)


Bog*_*dan 6

您不能在缓存中存储关系。您需要缓存从数据库中检索到的实际数据。所以你会有这样的事情:

public function roles()
{
    return \Cache::remember('user_' . $this->id . '_roles', 10, function()
    {
        return $this->hasMany('App\Role')->get()->toArray();
    });
}
Run Code Online (Sandbox Code Playgroud)

现在你必须将它作为方法而不是属性来访问,因为它不再返回关系(并且 Eloquent 会抛出异常):

$user->roles();
Run Code Online (Sandbox Code Playgroud)

现在你应该得到一个你想要的数组。