查询联结 table 而没有在 Sequelize 中获得两个关联

Query junction table without getting both associations in Sequelize

考虑以下模型:

var User = sequelize.define('User', {
  _id:{
    type: Datatypes.INTEGER,
    allowNull: false,
    primaryKey: true,
    autoIncrement: true
  },
  name: Datatypes.STRING,
  email:{
    type: Datatypes.STRING,
    unique: {
      msg: 'Email Taken'
    },
    validate: {
      isEmail: true
    }
  }
});

var Location= sequelize.define('Location', {
  _id:{
    type: Datatypes.INTEGER,
    allowNull: false,
    primaryKey: true,
    autoIncrement: true
  },
  name: Datatypes.STRING,
  address: type: Datatypes.STRING
});

Location.belongsToMany(User, {through: 'UserLocation'});
User.belongsToMany(Location, {through: 'UserLocation'});

有没有办法在 UserLocation table 中查询特定 UserId 并获得相应的 Locations。类似于:

SELECT * FROM Locations AS l INNER JOIN UserLocation AS ul ON ul.LocationId = l._id WHERE ul.UserId = 8

据我所知,您可以执行类似以下操作:

Location.findAll({
  include: [{
    model: User,
    where: {
      _id: req.user._id
    }
  }]
}).then( loc => {
  console.log(loc);
});

然而,这个 returns LocationsUserLocation 路口,以及 User 它正在加入 User table 当我不需要任何用户信息,我只需要该用户的 Locations。我所做的是有效的,但是,首选对联结 table 的查询而不是 User table.

上的查找

我希望这是清楚的。提前致谢。

编辑

实际上我最终以不同的方式实现了这一点。但是,我仍然打算将其作为一个问题,因为这应该是可能的。

将结点 table 声明为单独的 class,类似这样

var UserLocation = sequelize.define('UserLocation', {
  //you can define additional junction props here
});

User.belongsToMany(Location, {through: 'UserLocation', foreignKey: 'user_id'});
Location.belongsToMany(User, {through: 'UserLocation', foreignKey: 'location_id'});

然后你可以像查询其他模型一样查询路口table。