Sequelize.js:如何查询N:M关系

时间:2017-04-03 13:33:40

标签: javascript node.js sequelize.js

我在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',
});

我无法根据其位置查询工作机会:

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

错误:只有HasMany关联支持include.separate

我已经尝试了几乎我能在网上找到的任何解决方案,但似乎没有任何效果。想法?

1 个答案:

答案 0 :(得分:2)

不知怎的,我设法做到了:

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

不知道发生了什么,如果有人知道我想理解它:)