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

如何在带父子关系的Section模型中获取子章节的前后记录

解决同父子章节组内的上/下一条记录问题

嘿,你的问题很典型——当前的next()和previous()方法是全局范围内找ID相邻的记录,但我们需要的是同一个父章节下的兄弟子章节的前后项,对吧?而且既然你用了SortableTrait,应该是基于position字段来排序章节顺序的,所以我们要围绕这两个核心点来修改方法:

修改后的next()方法

public function next(){
    // 限定在同一个父级下,找position比当前大的第一条记录(按排序字段升序)
    return self::where('parent', $this->parent)
               ->where('position', '>', $this->position)
               ->orderBy('position', 'asc')
               ->first();
}

修改后的previous()方法

public function previous(){
    // 限定在同一个父级下,找position比当前小的最后一条记录(按排序字段降序取第一条就是紧邻的上一条)
    return self::where('parent', $this->parent)
               ->where('position', '<', $this->position)
               ->orderBy('position', 'desc')
               ->first();
}

为什么这么改?

  • 用where('parent', $this->parent)精准锁定范围:只在当前章节的兄弟章节(同父级)里查找,完美匹配你的父子关系需求;
  • 替换id为position作为排序依据:id是自增字段,和章节的实际展示顺序未必一致,而position是你通过SortableTrait维护的业务排序字段,更符合实际场景;
  • 自动兼容顶级章节:如果当前是无父级的顶级章节(parent为null或0),条件会自动匹配所有同级别顶级章节,无需额外判断。

如果你的排序字段不是position,只需要把代码里的position换成你实际使用的排序字段就可以啦!

内容的提问来源于stack exchange,提问作者user3574492

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:51:03