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

AdonisJs v5中如何使用preload()实现关联表字段的orderBy排序

AdonisJS v5 按关联表字段排序的实现方案

AdonisJS v5 的 preload 逻辑和 v4 的 with 存在差异,你可以根据实际需求选择以下两种实现方式:

场景1:仅对预加载返回的关联数据排序

如果只需要让每条Service对应的categories列表按id倒序排列,直接在preload的回调函数中写排序逻辑即可:

const services = await Service
  .query()
  .preload('categories', (categoriesQuery) => {
    categoriesQuery.orderBy('id', 'desc')
  })

场景2:主表Service的查询结果按关联表categories的字段排序

由于preload默认会拆分两次独立查询(先查主表、再查关联表),主查询链无法直接访问关联表字段,需要先手动关联表再排序:

const services = await Service
  .query()
  // 按需替换关联外键字段,示例假设services表用category_id关联categories表的id
  .join('categories', 'services.category_id', '=', 'categories.id')
  .orderBy('categories.id', 'desc')
  // 仍可通过preload获取完整的关联数据
  .preload('categories')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 02:06:06