【问题标题】:Query junction table without getting both associations in Sequelize查询联结表而不在 Sequelize 中获取两个关联
【发布时间】:2016-07-23 15:41:26
【问题描述】:

考虑以下模型:

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表中查询特定的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);
});

但是,当我不需要任何用户信息并且我只需要该用户的 Locations 时,这将返回 LocationsUserLocation 连接和 User,它正在加入 User 表。我所做的是工作,但是,首选对联结表的查询,而不是在 User 表上的查找。

我希望这很清楚。提前致谢。

编辑

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

【问题讨论】:

    标签: javascript mysql node.js express sequelize.js


    【解决方案1】:

    将联结表声明为单独的类,类似这样

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

    然后您可以像任何其他模型一样查询联结表。

    【讨论】:

    • 您能否提供使用 UserLocation 表的方式来准确生成 OP 询问的查询?谢谢。
    • 我现在无法尝试,因为我没有在这里直播续集项目。但我很确定您可以像使用任何其他表一样使用联结表,而不会损害关系定义。在最坏的情况下,您可以显式地在 UserLocation 上定义外键列,但我猜它们是由 sequelized 在类上定义的。 (类似于 id 列,自动声明,但如果你明确地重新声明它不会发生任何事情)之后你应该能够使用 UserLocation 作为基本外键并以相同的方式构造查询。
    • 这仍然不允许您在没有其他关联实体的情况下将关联实体之一与联结表连接起来。
    猜你喜欢
    • 2016-09-30
    • 2019-04-14
    • 2017-09-30
    • 2016-12-19
    • 1970-01-01
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多