Model filter tied by Sequelize

Asked

Viewed 136 times

-2

I have two models in my application, Delivery and Deliveryproblem. Deliveryproblem has a PK (delivery_id) of Delivery:

static associate(models) {
    this.belongsTo(models.Delivery, {
      foreignKey: 'delivery_id',
      as: 'delivery',
    });
  }

I need to select all Deliveries that have a Deliveryproblem. My method in the controller looks like this:

async index(req, res) {
    const response = await DeliveryProblem.findAll({
      order: ['id'],
      attributes: ['delivery_id'],
    });

    // Filtrando todos os ids de Encomendas que tenham algum problema
    const ids = [...new Set(response.map((x) => x.delivery_id))];

    const deliveries = Delivery.findAll({
      where: , // <<< Como filtrar os ids aqui ?
      order: ['id'],
    });

    return res.json(deliveries);
  }

1 answer

1


Solved as follows, using the Sequelize Op:

const Sequelize = require('sequelize')
const Op = Sequelize.Op
...
// Filter all Deliveries with problem
const ids = [...new Set(response.map((x) => x.delivery_id))];
const deliveries = Delivery.findAll({
  where: {
   id: {
     [Op.in]: ids
   }
  },
  order: ['id'],
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.