Sequelize WHERE NOT EXISTS()

4
我有一个多对多关系,看起来像这样:

var Genres = db.define('Movie', {
    name: {
        type: Sequelize.STRING(100),
        allowNull: false
    },
    description: {
        type:Sequelize.STRING(),
        allowNull: true
    },
    thumbnail: {
        type: Sequelize.BLOB(),
        allowNull: true
    },
    urlposter: {
        type: Sequelize.STRING(245),
        allowNull: true
    }
});
var Users = db.define('User', {
    username: {
        type: Sequelize.STRING(25),
        allowNull: false
    },
    password: {
        type: Sequelize.STRING(25),
        allowNull: false
    }
});
Movies.belongsToMany(Users, {through: UM, foreignKey: 'Id_Movies'});
Users.belongsToMany(Movies, {through: UM, foreignKey: 'Id_Users'});

我将返回所有未关联到特定用户的电影。
这是我想要实现的SQL查询:
SELECT m.* 
FROM Movies m 
WHERE NOT EXISTS(SELECT NULL 
FROM Users_Movies sc 
WHERE sc.Id_Movies = m.id AND sc.Id_Users = 1)

这是我最接近的,但这只返回所有电影中与用户ID 1相关的链接。
            Movies.findAll({
            include: [
            // {
            //  model:Genres,
            //  through:{attributes:[]}
            // },
            {
                model:Users,
                through:{attributes:[]},
                where: {id: 1},
                required: true,
            }],
        })
        .then(function(movies){
            done(null, movies);
        })
        .catch(function(error){
            done(error, null);
        });

但我想反过来。

目前我的唯一选择是进行两个查询,一个查询所有电影,另一个查询所有具有链接的电影,并循环遍历列表并将它们从第一个列表中删除... 这不是优美的代码。


你说你想获取所有没有与特定用户关联的电影,但是你想要实现的SQL语句中却有“AND sc.Id_Users = 1”。这不是和特定用户相关联的吗? - user1477388
不,它不是...如果你运行它,它将返回所有未绑定到id为1的用户的电影。 - Adam
从包含的用户模型中删除 required: true,并将 where: {'Users.id': null} 添加到查询中。我不确定确切的字段命名,但我认为你已经明白了这个想法。 - Alexandr Zarubkin
2个回答

4

我知道我来晚了,但我认为在查询的“where”子句中使用文字'users.id IS NULL'就可以解决问题:

 Movie.findAll({
    where: sequelize.literal("users.id IS NULL"),
    include: [
      {
        model: Users,
        through: { attributes: [] }
      }],
  })
    .then(function (movies) {
      done(null, movies);
    })
    .catch(function (error) {
      done(error, null);   
    });

本解决方案基于以下 Github 问题: https://github.com/sequelize/sequelize/issues/4099

0
使用 rawQuery。
const projects = await sequelize.query('SELECT * FROM projects', {
  model: Projects,
  mapToModel: true // pass true here if you have any mapped fields
});

你的回答可以通过添加更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心找到有关如何编写良好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接