Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize ORM include model only if active = true

how can I findAll orders with id: 1 and include items only if this item has active = true? Otherwise there will be empty array...

Order.findAll({
    where: { id: 1 },
    include: [
      { model: Item, where: sequelize.and({'active' : true }) }
    ]
}).then(function(order) {
    callback(null, order);
});

This shows me only orders where are some items with active = true. I wanted to show all orders with id: 1 and items as a sub-array ...

like image 704
Makromat Avatar asked May 06 '26 05:05

Makromat


1 Answers

From Sequelize Tutorial:

Adding a where clause to the include automatically makes it required

The solution is this:

Order.findAll({
    where: { id: 1 },
    include: [
      { model: Item, 
        where: sequelize.and({'active' : true }),
        required: false 
      }
    ]
}).then(function(order) {
    callback(null, order);
});
like image 56
Makromat Avatar answered May 08 '26 09:05

Makromat



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!