Laravel中为关联关系添加分页并获取关联的关联数据实现方案
正确实现方案
这里提供两种常用的可行写法:
方案1:直接查询Post模型(更推荐)
你核心需要的是分页的帖子列表,直接从Post表查询逻辑更简洁,代码如下:
<?php namespace App\Services; use App\Models\Post; class ForumService { public static function getForumPosts($forumId) { // 直接查询指定论坛下的帖子,预加载对应用户,按发布时间倒序分页 return Post::with('user') ->where('forum_id', $forumId) ->orderBy('created_at', 'DESC') ->paginate(10); } }
这个方法返回标准的分页器实例,每个条目都是带user关联数据的Post模型,如果你同时需要论坛的基础信息,再加个->with('forum')预加载即可。
方案2:先查Forum实例再绑定分页关联
如果你必须先获取Forum实例,再挂载其下的分页帖子,可手动给模型设置关联:
<?php namespace App\Services; use App\Models\Forum; class ForumService { public static function getForumPosts($forumId) { $forum = Forum::findOrFail($forumId); // 手动查询帖子、预加载用户、分页后赋值给forum的posts关联 $forum->setRelation('posts', $forum->posts()->with('user')->paginate(10)); return $forum; } }
原写法错误原因
你之前的写法之所以不行,是因为with()预加载的闭包内仅支持添加查询约束,不能调用paginate方法:Laravel预加载关联的逻辑是先查询主表(forums),再用主表ID批量查询关联表(posts)后做匹配,闭包内分页会破坏关联匹配逻辑,也无法在这个层级嵌套加载posts下的user关联。
内容的提问来源于stack exchange,提问作者algorithm19
相关产品推荐
相关产品推荐

