Sequelize - How to get entries from one table that are not assiciated by another table

拈花ヽ惹草 提交于 2019-12-24 17:18:35

问题


I used Sequelize to define three Entities for users rating posts:

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

A user can rate several posts. Each rating belongs to exactly one user and one post.

Now I'd like to query for a given user all posts that are not already rated by this user. I tried a thousand ways but without success. Any idea how to achieve this in Sequelize? Thanks a lot!


回答1:


There are two methods either use raw query in Sequelize or via Sequelize query as well -

Raw -

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

Sequelize -

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


来源:https://stackoverflow.com/questions/54630747/sequelize-how-to-get-entries-from-one-table-that-are-not-assiciated-by-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!