Makromat
Makromat

Reputation: 1572

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 ...

Upvotes: 3

Views: 5351

Answers (1)

Makromat
Makromat

Reputation: 1572

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);
});

Upvotes: 5

Related Questions