gpt4 book ai didi

php - 缓存 Eloquent 关系查询

转载 作者:行者123 更新时间:2023-12-02 03:09:03 24 4
gpt4 key购买 nike

如何缓存此 Eloquent 查询:

dd($user->roles);

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

我已经尝试过这个:

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

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

有什么建议吗?

最佳答案

这是针对现代 Laravel 更新的方法:

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

// Define the cache key (as its used in multiple places)
protected function getBookmarksCacheKey(): string
{
return sprintf('user-%d-bookmarks', $this->id);
}

// Provide a cache clearing mechanism
public function clearBookmarksCache(): bool
{
return Cache::forget($this->getBookmarksCacheKey());
}

// Override the relation property getter
// It will return the cached collection when it exists, otherwise getting a fresh one from the database
// It then populates the relation with that collection for use elsewhere
public function getBookmarksAttribute(): Collection
{
// If the relation is already loaded and set to the current instance of model, return it
if ($this->relationLoaded('bookmarks')) {
return $this->getRelationValue('bookmarks');
}

// Get the relation from the cache, or load it from the datasource and set to the cache
$bookmarks = Cache::rememberForever($this->getBookmarksCacheKey(), function () {
return $this->getRelationValue('bookmarks');
});

// Set the relation to the current instance of model
$this->setRelation('bookmarks', $bookmarks);

return $bookmarks;
}

关于php - 缓存 Eloquent 关系查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28844611/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com