使用动态查询构建的Adonis js分页

时间:2019-09-16 06:59:18

标签: adonis.js

我正在建立这样的查询

    let searchData = request.all()

    let products =  Product.query().where('product_type', searchData.type).with('singleImage').paginate(1, 20)

    if(parseInt(searchData.minPrice) > 0 && parseInt(searchData.maxPrice) > 0) {
        products.where("lowerPrice", ">=", searchData.minPrice).where("upperPrice", "<=", searchData.maxPrice)
    }

    // more conditions and query goes here 

由于.paginate(1, 20),它不起作用,如果我删除了分页符,它会起作用。

1 个答案:

答案 0 :(得分:1)

你需要在把所有条件都设置好后执行 paginate 或 fetch。例如:

let searchData = request.all()

let products = Product.query()
          .where('product_type',searchData.type)
          .with('singleImage')
// Remove pagination from here

if(parseInt(searchData.minPrice) > 0 && parseInt(searchData.maxPrice) > 0) 
{
 products.where("lowerPrice", ">=", searchData.minPrice)
         .where("upperPrice", "<=", searchData.maxPrice)
}

// Put all your conditions 


// Finally execute paginate with await or yield it depends of adonis version (await or yield)

products = await products.paginate(1,20)