You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 04:54:00