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

Adonis 5 TS中如何按用户类型控制查询是否执行分页?

Adonis 5 TypeScript 条件分页问题解决

你的问题核心是:使用Adonis 5的.if()方法时,在回调内调用paginate()无法生效,因为paginate()是终止查询的方法,而.if()的回调仅用于构建查询条件链,不会直接执行终止操作。

直接拆分逻辑即可解决,因为分页返回的是分页对象,不分页返回的是数据数组,分开处理不仅逻辑清晰,还能保证类型正确:

// 先构建通用的查询条件链
const baseQuery = queryBuilder
  .where((query) => {
    if (productCategory) {
      query.where('targetType', productCategory)
    }
    if (dataForFilter.registerDateFrom) {
      query.where('createdAt', '>=', dataForFilter.registerDateFrom)
    }
    if (dataForFilter.registerDateTo) {
      query.where('createdAt', '<=', dataForFilter.registerDateTo)
    }
    // 其他筛选条件...
  })
  .preload('package', (query) => {
    query.preload('product', (query) => {
      query.preload('productCategory')
      query.preload('company')
    })
  })
  .orderBy('createdAt', 'desc')

// 根据用户类型执行不同查询操作
if (dataForFilter.userTypeResultData.userType === 'Insurance') {
  policies = await baseQuery.paginate(page, limit)
} else {
  // fetch() 返回所有匹配结果的数组,对应Admin用户无需分页的需求
  policies = await baseQuery.fetch()
}

为什么原来的写法不生效?

Adonis 5的.if()方法是用于链式添加查询条件(比如where、preload这类),它的回调接收的query实例是当前查询链的引用,但paginate()是直接触发查询并返回结果的终止方法,无法通过.if()的链式调用传递结果。拆分逻辑后,直接根据条件调用对应的终止方法,就能正确获取所需结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 11:52:54