我有一个多对多关系,看起来像这样:
我将返回所有未关联到特定用户的电影。
这是我想要实现的SQL查询:
这是我最接近的,但这只返回所有电影中与用户ID 1相关的链接。
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);
});
但我想反过来。
目前我的唯一选择是进行两个查询,一个查询所有电影,另一个查询所有具有链接的电影,并循环遍历列表并将它们从第一个列表中删除... 这不是优美的代码。
required: true
,并将where: {'Users.id': null}
添加到查询中。我不确定确切的字段命名,但我认为你已经明白了这个想法。 - Alexandr Zarubkin