Conditional filter using Knex.js and SQL with multiple search criteria
You can conditionally build your query with the knex query builder:
const getFilteredItems = (searchCriteria) => knex('items')
.where((qb) => {
if (searchCriteria.searchTerm) {
qb.where('items.itemName', 'like', `%${searchCriteria.searchTerm}%`);
}
if (searchCriteria.itemType) {
qb.orWhere('items.itemType', '=', searchCriteria.itemType);
}
if (searchCriteria.category) {
qb.orWhere('items.category', '=', searchCriteria.category);
}
});
You can also use this
instead of accepting a querybuilder argument as in the example @abdulbarik gave, but I think it is less explicit.
You can try the following :
const getFilteredItems = (searchCriteria) => knex('items')
.where('items.itemName', 'like', `%${searchCriteria.searchTerm || ''}%`)
.where('items.itemType', 'like', `%${searchCriteria.itemType || ''}%`)
.where('items.category', 'like', `%${searchCriteria.category || ''}%`)
If any parameter is missing or undefined
, it will match the field to be like '%%'
which effectively means, don't care about this parameter.