试图弄清楚如何使knex查询更加灵活和可重用,但目前却无济于事。
我有一个带有方法的类
getBaseCollege(recordsType, fileTypes, cond1, cond2) {
const knex = this.knex;
return knex.countDistinct('q.p').from(function () {
this.distinct(recordsType)
.select()
.from('dbo.Person as p')
.leftJoin('CollegeDisciplines as cd', 'cd.PID', 'parent_o.PID')
.whereIn('o.fileType', fileTypes)
.andWhere(knex.raw(`(CASE od.ProfessionalType WHEN '09' THEN x.CWB_OrganizationClassID ELSE 0 END) != '8'`))
.where('b.priority', '!=', '8')
// here I want to have optional condition like .andWhere(knex.raw(cond1)
.as('q')
.unionAll(function () {
this.distinct(recordsType)
.select()
.from('dbo.Person as p')
.leftJoin('dbo.CollegeDisciplines as cd', 'cd.PID', 'o.PID')
.whereIn('o.fileType', fileTypes)
.andWhere(knex.raw(`(CASE od.ProfessionalType WHEN '09' THEN x.CWB_OrganizationClassID ELSE 0 END) != '8'`))
.where('b.priority', '!=', '8')
// here I want to have the second optional condition like .andWhere(knex.raw(cond2)
}).as('q')
});
}
目的是当我不需要任何条件而只需要常规查询时,将此方法与andwithout(cond1,cond2)参数一起使用。我该如何实现?
答案 0 :(得分:0)
请查看.clone()
函数here,该函数可让您重用查询。
例如,您可以在基本查询之后添加.clone()
,然后添加所需的条件,最后等待查询被解决。
let query = this
.from('users')
.where('username', 'agtabesh')
.clone()
// later
query = query.where('active', 1)
await query