php - 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 页面,帖子仍然存在(因为它们被缓存)但不是它们的文件。所以我的问题是我如何查询它以使文件也被存储?
解决方案
用于with
将关系附加到查询结果
$posts = Post::with('files')
->orderBy('updated_at', 'desc')
->where('board', $nomeBoard)
->where('lead_id', null)
->paginate(10);
推荐阅读
- mysql - 设计数据库并使用 mySQL 进行查询 - 不确定我是否正确建模?
- python - 如何从函数中的 pytest 夹具获取返回值,因此我不需要使用附加参数调用此函数?
- node.js - Nodejs unittest 模拟量角器 $ 模块
- doctrine-orm - 在结果中嵌入关系
- sql - 根据条件将正确的值作为一个变量提取
- python - 从字符串 url 打开新选项卡
- ios - Unity3D 导出的源代码:C++ 头文件无法识别
- python - 使用 int() 错误
- java - Spring Cloud Contract:为具有不同或部分不同期望的多个消费者编写合约测试
- bash - 匹配并复制同名目录的内容到同名的新目录?