【问题标题】:Laravel - Cache results of relationship tables using Eloquent queriesLaravel - 使用 Eloquent 查询缓存关系表的结果
【发布时间】:2018-07-15 16:47:19
【问题描述】:

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

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

【问题讨论】:

    标签: php laravel laravel-5.6


    【解决方案1】:

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

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

    【讨论】:

    • 这称为预加载关系(参考 Laravel 文档)
    猜你喜欢
    • 1970-01-01
    • 2021-09-25
    • 2021-10-26
    • 2013-10-03
    • 2017-07-19
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    • 2015-01-21
    相关资源
    最近更新 更多