当关系不使用主键时,Sequelize属于ToMany

时间:2017-05-14 13:16:49

标签: sequelize.js

我正在构建社交网络,因此我的模型是帖子,用户和用户跟随用户关系

var User = sequelize.define('user', {
  username: Sequelize.DataTypes.STRING
})

var Post = sequelize.define('post', {
  text: Sequelize.DataTypes.STRING,
  userId: Sequelize.DataTypes.INTEGER 
})

var Follow = sequelize.define('follow', {
    followerUserId: Sequelize.DataTypes.INTEGER,
    followingUserId: Sequelize.DataTypes.INTEGER,
  })

为了获取某个用户的Feed - 来自他们关注的用户的所有帖子 - 我需要能够执行看起来像这样的查询:

User.findById(13).then(user => user.getFollowingPosts())

但是我坚持这个协会:

User.belongsToMany(Post, {
      as: 'followingPosts',
      through: { model: Follow, },
      foreignKey: 'followerUserId',
      otherKey: 'userId',
    });

生成错误的SQL JOIN条件,我无法修复:

SELECT ...
FROM `posts` AS `post` INNER JOIN `follows` AS `follow`
  ON `post`.`id` = `follow`.`userId` AND `follow`.`followerUserId` = 13

我无法使用Sequelize post.userId 而非 post.id

1 个答案:

答案 0 :(得分:0)

Found a good enough workaround:

Post.belongsTo(Follow, {
  as: 'following',
  foreignKey: 'userId',
  targetKey: 'followingUserId',
  allowNull: false
})

This way I skip User.blongsToMany altogether and query the followships:

Post.findAll({
  include: [{
    association: Post.associations.following,
    where: { followerUserId: 13}
  }]
})

Which generates:

SELECT ...
FROM `posts` AS `post` INNER JOIN `follows` AS `following`
  ON `post`.`userId` = `following`.`followingUserId` AND
     `following`.`followerUserId` = 13