我有一个多对多的关系,如下所示:
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);
});
但我想反转它。
现在我唯一的选择是进行两个查询,一个查询所有电影,一个查询所有有链接的电影,循环遍历列表并将它们从第一个列表中删除。这不是漂亮的代码。
最佳答案
我知道我在这件事上迟到了,但我认为在查询的“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
关于javascript - 序列化 WHERE NOT EXISTS(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33844422/