简体   繁体   中英

Knex query partition with conditions

Trying to figure out how to make knex query more flexible and reusable but currently down the drain.

I have a class with a method

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')
            });
    }

The purpose is to use this method with and WITHOUT (cond1, cond2) arguments when I don't need any condition but just regular query. How can I achieve it?

Please take a look at .clone() function here which allows you to reuse a query.

For example you can add .clone() after your base query then add whatever condition you need and finally wait for query to be resolved.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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