Skip to content
Advertisement

How to add if statement in knex.select()?

I have code like this

const attr = req.query.attr
knex.select(knex.raw('foo_name as name'))

what I want is somehow select that column if it meets condition of attr and if does not then do select nothing. Something like:

knex.select(if(attr == foo){knex.raw()})

Advertisement

Answer

You can assign the selection on other variable and then pass it to kenx.select.

const selection = attr == foo ? knex.raw('bla') : knex.raw('');
await knex.select(selection);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement