Sequelize.js: How to query an N: M relationship

I have the following relationship in sequel:

Location.Offers = Location.belongsToMany(JobOffer, {
  foreignKey: 'locationId',
  through: 'JobOffer_Location',
  as: 'offers',
});

JobOffer.Locations = JobOffer.belongsToMany(Location, {
  foreignKey: 'jobOfferId',
  through: 'JobOffer_Location',
  as: 'locations',
});

      

I cannot request a job offer based on its location, though:

const locations = [1, 2]
JobOffer.findAll({
  include: [{
    model: Location,
    as: 'locations',
    where: {
      locationId: {
        $in: locations
      }
    },
  }],
})

      

Error: Only HasMany associations support include.separate

I've tried almost every solution I could find on the internet, but nothing seems to work. Ideas?

+3


source to share


1 answer


Somehow I managed it:

order: [
  ["createdAt", "DESC"],
],
limit: limit,
offset: parsePage(args.page || 1, limit),
include: [{
  model: Location,
    as: 'locations',
    separate: false,
    attributes: [],
    duplicating: false,
  }],
where: {
  '$locations.id$': {
    $in: args.locations
  }
},

      



https://github.com/sequelize/sequelize/issues/4446

Don't know what's going on if someone knows that I would like to understand it :)

+1


source







All Articles