首页 > 解决方案 > Laravel - 使用 Eloquent 查询缓存关系表的结果

问题描述

我在我的应用程序中有一个简单的关系 Post x Files(一篇文章有​​很多文件,一个文件只与一篇文章相关联)。为了使事情更灵活,我将帖子存储在缓存中,只要它没有更改,我就不需要再次查询数据库。我注意到的问题是只有帖子存储在缓存中,而不是文件(我想问题是因为我查询它们的方式)。我的代码是:

class Post extends Model
{

public function files(){
    return $this->hasMany('Ibbr\File');
}

}

获取帖子的功能:

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 页面,帖子仍然存在(因为它们被缓存)但不是它们的文件。所以我的问题是我如何查询它以使文件也被存储?

标签: phplaravellaravel-5.6

解决方案


用于with将关系附加到查询结果

$posts = Post::with('files')
    ->orderBy('updated_at', 'desc')
    ->where('board', $nomeBoard)
    ->where('lead_id', null)
    ->paginate(10);

推荐阅读