Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize.js: How to query N:M relation

I have the following relations in sequelize:

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'm not being able to query 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 have tried almost any solution I could find online, but nothing seems to work. Ideas?

like image 639
Fábio Santos Avatar asked Oct 17 '22 14:10

Fábio Santos


1 Answers

Somehow I managed to do 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

No idea what's going on though, if someone knows I would like to understand it :)

like image 160
Fábio Santos Avatar answered Oct 20 '22 22:10

Fábio Santos