Sequelize-如何从一个表中获取未被另一表关联的条目

时间:2019-02-11 12:34:58

标签: node.js orm sequelize.js

我使用Sequelize为用户评分帖子定义了三个实体:

var User = sequelize.define('User', {
  email:  {
    type: Sequelize.STRING,
    primaryKey: true
  }
});

var Post = sequelize.define('Post', {
  link: {
    type: Sequelize.STRING,
    primaryKey: true
  }
});

var Rating = sequelize.define('Rating', {
  result: Sequelize.STRING
});

Rating.belongsTo(Post);
Post.hasMany(Rating);

Rating.belongsTo(User);
User.hasMany(Rating);

用户可以对多个帖子进行评分。每个评分恰好属于一个用户和一个帖子。

现在,我想查询给定用户的所有尚未对此用户评分的帖子。我尝试了一千种方法,但没有成功。知道如何在Sequelize中实现吗?非常感谢!

1 个答案:

答案 0 :(得分:0)

有两种方法可以在Sequelize中使用原始查询,也可以通过Sequelize查询-

原始-

return Db.sequelize.query("SELECT * FROM Post P WHERE (P.id NOT IN (SELECT postId FROM Ratings R WHERE R.userId="+userId+")) ",{ type: Sequelize.QueryTypes.SELECT });

续集-

return Post.findAll({
where: {
Sequelize.literal("(posts.id NOT IN (SELECT R.postId FROM Rating R WHERE R.userId="+userId+"))")
}
});