Laravel - 使用 Eloquent 查询缓存关系表的结果
Laravel - Cache results of relationship tables using Eloquent queries
我在我的应用程序中有一个简单的关系 Post x 文件(一个 post 有很多文件,一个文件只与一个 post 相关联)。为了使事情更敏捷,我将 post 存储在缓存中,只要它没有改变,这样我就不需要再次查询数据库。我注意到的问题是只有 Posts 被存储在缓存中而不是文件(我想问题是因为我查询它们的方式)。我的代码是:
class Post extends Model
{
public function files(){
return $this->hasMany('Ibbr\File');
}
}
获取post的函数:
public static function pegaPostsBoard($nomeBoard)
{
$chave = 'posts_board';
if(Cache::has($chave))
return Cache::get($chave);
$posts = Post::orderBy('updated_at', 'desc')->where('board', $nomeBoard)->where('lead_id', null)->paginate(10);
Cache::forever($chave, $posts); //I "forget" the cache whenever the post is changed
return $posts;
}
我也尝试在将其添加到缓存之前添加 ->join('files', 'posts.id', '=', 'files.post_id')
,但没有成功。我怎么注意到文件没有被缓存?好吧,我重置了数据库,因此它清除了所有行,我注意到如果我 F5 页面,posts 仍然存在(因为它们被缓存)但不是它们的文件。所以我的问题是如何以文件也被存储的方式查询它?
使用with
将关系附加到查询结果
$posts = Post::with('files')
->orderBy('updated_at', 'desc')
->where('board', $nomeBoard)
->where('lead_id', null)
->paginate(10);
我在我的应用程序中有一个简单的关系 Post x 文件(一个 post 有很多文件,一个文件只与一个 post 相关联)。为了使事情更敏捷,我将 post 存储在缓存中,只要它没有改变,这样我就不需要再次查询数据库。我注意到的问题是只有 Posts 被存储在缓存中而不是文件(我想问题是因为我查询它们的方式)。我的代码是:
class Post extends Model
{
public function files(){
return $this->hasMany('Ibbr\File');
}
}
获取post的函数:
public static function pegaPostsBoard($nomeBoard)
{
$chave = 'posts_board';
if(Cache::has($chave))
return Cache::get($chave);
$posts = Post::orderBy('updated_at', 'desc')->where('board', $nomeBoard)->where('lead_id', null)->paginate(10);
Cache::forever($chave, $posts); //I "forget" the cache whenever the post is changed
return $posts;
}
我也尝试在将其添加到缓存之前添加 ->join('files', 'posts.id', '=', 'files.post_id')
,但没有成功。我怎么注意到文件没有被缓存?好吧,我重置了数据库,因此它清除了所有行,我注意到如果我 F5 页面,posts 仍然存在(因为它们被缓存)但不是它们的文件。所以我的问题是如何以文件也被存储的方式查询它?
使用with
将关系附加到查询结果
$posts = Post::with('files')
->orderBy('updated_at', 'desc')
->where('board', $nomeBoard)
->where('lead_id', null)
->paginate(10);