必须采用嵌套查询缓存优化策略:用cache::remember包裹完整with链并构造语义化键;db查询用cache()方法加缓存;通过模型观察器监听变更并用标签联动清除缓存。

当Laravel中出现多层嵌套查询(如with('posts.comments.user'))导致缓存键冲突、命中率低或关联数据更新后缓存未失效时,必须采用针对性的嵌套查询缓存优化策略,否则数据库负载会持续升高,响应延迟不可控。
用remember()配合自定义键名精准控制嵌套缓存
嵌套查询本身不支持链式remember()直接生效,必须将整个with()链包裹在Cache::remember闭包中,否则子查询不会被缓存。
第一步:构造带业务语义的缓存键,包含所有影响结果的变量,例如用户ID和分页偏移量:【'user:profile:posts:comments:with_user:'.$userId.':page_'.$page】
第二步:在闭包内执行完整嵌套查询,确保with()调用在get()之前:Cache::remember($key, 1800, function () use ($userId, $page) { return User::with(['posts.comments.user'])->where('id', $userId)->firstOrFail()->posts()->paginate(10, ['*'], 'page', $page); });
第三步:避免在闭包中调用模型事件或触发额外查询——这会导致缓存值污染且无法序列化。
用Query Builder的cache()方法为深层join查询加缓存
适用于含多表JOIN、子查询或selectRaw的嵌套逻辑,比Eloquent更可控。
方法一:直接在DB查询链末尾加cache()
DB::table('users')->join('posts', 'users.id', '=', 'posts.user_id')->join('comments', 'posts.id', '=', 'comments.post_id')->select('users.name', 'posts.title', DB::raw('COUNT(comments.id) as comment_count'))->groupBy('users.name', 'posts.title')->cache(3600)->get();
方法二:指定自定义缓存键,便于后续主动清除
->cache(7200, 'nested:users_posts_comments_summary')
【注意:cache()仅对get()、first()、value()等终端方法生效;调用toSql()或dump()不会写入缓存】
用模型观察器联动清除嵌套缓存
当任意嵌套层级的数据变更(如评论被删除),必须同步清除上层缓存,否则展示脏数据。
在App\Observers\CommentObserver.php中监听deleted事件:
public function deleted(Comment $comment)
{
Cache::forget('user:profile:posts:comments:with_user:'.$comment->post->user_id.':page_1');
Cache::tags(['user_'.$comment->post->user_id, 'post_'.$comment->post_id])->flush();
}
必须提前为相关缓存打标签,否则无法按业务维度批量清理。
在缓存写入时使用tags()方法:
Cache::tags(['user_'.$userId, 'post_'.$postId])->remember('comment_list_'.$postId, 3600, fn() => $commentQuery->get());











