Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize where query with ternary operator

I want to make a findAll query with Sequelize and I want to pass where conditions dynamically based on parameters rather than writing many if-else statements, is there a way to discard a condition if the passed value is null? (See the [Op.gt] and [Op.lte] below.)

Transaction.findAll({
    limit: limit ? limit : 20,
    where: {
        id: id,
        approved: true,
        [Op.gt]: from ? from : null,
        [Op.lte]: to ? to : null
    }
})

Running the above code gives this error:

s.replace is not a function

like image 532
Fawaz Aljohani Avatar asked May 13 '26 02:05

Fawaz Aljohani


1 Answers

You can use spread operator:

Transaction.findAll({
    limit: limit || 20,
    where: {
        id: id,
        approved: true,
        ...(from ? { [Op.gt]: from } : {}),
        ...(to ? { [Op.lte]: to } : {})
    }
})
like image 189
An Nguyen Avatar answered May 14 '26 16:05

An Nguyen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!