繁体   English   中英

具有条件的Knex查询分区

[英]Knex query partition with conditions

试图找出如何使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')
            });
    }

目的是当我不需要任何条件而只需要常规查询时,使用带有和WITHOUT(cond1,cond2)参数的方法。 我怎样才能实现它?

请查看.clone()函数它允许您重用查询。

例如,您可以在基本查询之后添加.clone() ,然后添加所需的任何条件,最后等待查询得到解决。

let query = this
  .from('users')
  .where('username', 'agtabesh')
  .clone()

// later
query = query.where('active', 1)
await query

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM