knex like query dynamically add

核能气质少年 提交于 2019-12-04 17:36:51

You can add parts of queries like this:

const getResults = (options) => {
    let query = knex('table');
    if (options.where) {
        query = query.where('franchisee_name', 'like', '%jackmarker%');
    }

    if (options.other) {
        query = query.where('company', 'like', '%marker%');
    }

    return query.select();
};

You can also use raw queries like this:

const getVehiclePolicies = (options) => {
    return P.try(() => {
        const queries = [
            `
                SELECT
                    vp.id AS vehicle_policy_id,
                    vp.policy_id,
                    vp.policy_number,
                    vp.status,
                    vp.service_count,
                    vp.manufacturer,
                    vp.model,
                    vp.variant,
                    vp.colour,
                    vp.year,
                    vp.policy_owner,
                    vp.policy_owner_email,
                    vp.policy_owner_phone,
                    vp.policy_owner_country_code,
                    vp.vin_number,
                    vp.engine_number,
                    vp.vehicle_type,
                    vp.start_date,
                    vp.end_date,
                    vp.expired,
                    vp.created_at,
                    vp.updated_at
                FROM vehicles AS v
                    INNER JOIN vehicle_policies AS vp ON v.registration_number = vp.vehicle_id
                    INNER JOIN company_policies AS cp ON cp.id = vp.policy_id
                WHERE
                    NOT v.deleted
                    AND NOT vp.deleted
                    AND NOT cp.deleted              
            `
        ];

        const bindings = [];

        if (options.vehicle_id) {
            queries.push('AND vp.vehicle_id = ?');
            bindings.push(options.vehicle_id);
        }

        if (options.policy_number) {
            queries.push('AND vp.policy_number = ?');
            bindings.push(options.policy_number);
        }

        if (options.vehicle_policy_id) {
            queries.push('AND vp.id = ?');
            bindings.push(options.vehicle_policy_id);
        }

        if (options.default_policy) {
            queries.push('AND cp.default_policy');
        }

        queries.push(`LIMIT ? OFFSET ?`);
        bindings.push(options.limit || 15);
        bindings.push(options.offset || 0);

        return db.raw(queries.join(' '), bindings);
    }).then((data) => {
        debug('GET VEHICLE POLICIES DATA');
        debug(data.rows);

        return data.rows;
    });
};

You can use a shorthand Query Builder like

Const fname = () =>knex(tableName)
.where(builder=>
builder.whereIn('id', [1, 11, 15]).whereNotIn('id', [17, 19]))
.andWhere(()=> {
If(condition)this.where('id', '>', 10)
}))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!