如果我想从给定以下参数的表中获取所有列,以下分页查询可以正常工作
getOrdersPagination(limit, after) {
let where = '';
if (after > 0) {
where = `id < ${after}`;
}
return knex
.select(
'id',
'patient_id AS patientId',
'pharmacy_id AS pharmacyId',
'customer_id AS customerId',
'department_id AS departmentId',
'user_id AS userId',
'status',
'info',
'created_at AS createdAt'
)
.from('order')
.whereRaw(where)
.orderBy('id', 'desc')
.limit(limit);
}
但是,如果我传递另一个参数(在本例中为status
)以进一步过滤掉返回的行,我将获得与上述查询完全相同的输出。 status
字段(整数)对我的getOrdersByStatusPagination
查询没有任何影响。
getOrdersByStatusPagination(limit, after, status) {
let where = '';
if (after > 0) {
where = `id < ${after} AND status = ${status}`;
}
return knex
.select(
'id',
'patient_id AS patientId',
'pharmacy_id AS pharmacyId',
'customer_id AS customerId',
'department_id AS departmentId',
'user_id AS userId',
'status',
'info',
'created_at AS createdAt'
)
.from('order')
.whereRaw(where)
.orderBy('id', 'desc')
.limit(limit);
}
我想知道我是否正确使用whereRaw
子句来使用AND
运算符包含多个where语句。
http://knexjs.org/#Builder-whereRaw
我还可以包含查询的示例JSON输出,但我不确定这是否有任何帮助,因为它只是从提到的列中获取所有数据。
答案 0 :(得分:0)
我发现的一个解决方案是在查询中使用另一个where
子句以及whereRaw
。但我还是想听听有人知道如何在status
选项中使用whereRaw
arg
另一个where
子句的解决方案
getOrdersByStatusPagination(limit, after, status) {
let where = '';
if (after > 0) {
where = `id < ${after}`;
}
return knex
.select(
'id',
'patient_id AS patientId',
'pharmacy_id AS pharmacyId',
'customer_id AS customerId',
'department_id AS departmentId',
'user_id AS userId',
'status',
'info',
'created_at AS createdAt'
)
.from('order')
.whereRaw(where)
.where('status', '=', status)
.orderBy('id', 'desc')
.limit(limit);
}
答案 1 :(得分:0)
所以,这是解决问题的knex
方法
基本理念是。您创建knex
构建器的实例并有条件地向其添加子句。
getOrdersByStatusPagination (limit, after, status) {
const builder = knex
.select(
'id',
'patient_id AS patientId',
'pharmacy_id AS pharmacyId',
'customer_id AS customerId',
'department_id AS departmentId',
'user_id AS userId',
'status',
'info',
'created_at AS createdAt'
)
.from('order')
.whereRaw(where)
.where('status', status) // No need for '=' argument. Knex inserts it by default
.orderBy('id', 'desc')
.limit(limit);
if (after > 0) {
builder.where('id', '<', after) // No need for .whereRaw method. You can use the same as for statuses' '='
// or builder.whereRaw(`id < ${after}`)
}
return builder
}