我有3个模型:Post
,Photo
和Audio
。
帖子可以有照片或音频剪辑(或两者都没有):
models.Post.hasOne(models.Photo, { as: 'photo' });
models.Post.hasOne(models.Audio, { as: 'audio' });
我正在尝试选择那些既没有 - 也就是文本帖子。我一直在挖掘,我到了(从here获取信息):
db.Post.findAll({
where: {
'$photo.id$': { $eq: null },
'$audio.id$': { $eq: null }
},
order: [
['createdAt', 'DESC']
],
include: [{... "photo" and "audio" - both with required: true}],
}).then((posts) => {
...
});
然而,这似乎不起作用(我不认为我完全理解相关模型是如何被引用的)。此外,生成的查询使用INNER JOINS
而不是LEFT JOINS
,因此当它尝试加入Posts
和Photos
/ Audios
时,会生成一个空结果,而不是Post
的所有值以及Photo
和Audio
的空列的结果。
生成的查询是:
SELECT ... FROM (
SELECT *
FROM "Posts" AS "Post"
INNER JOIN "Photos" AS "photo"
ON "Post"."id" = "photo"."postId"
INNER JOIN "Audios" AS "audio"
ON "Post"."id" = "audio"."postId"
WHERE
"photo"."id" IS NULL AND
"audio"."id" IS NULL
) AS ...
查询
SELECT *
FROM "Posts" AS "Post"
LEFT JOIN "Photos" AS "photo"
ON "Post"."id" = "photo"."postId"
LEFT JOIN "Audios" AS "audio"
ON "Post"."id" = "audio"."postId"
WHERE
"photo"."id" IS NULL AND
"audio"."id" IS NULL
生成我正在寻找的结果集。我认为我的问题是每个包含模型的include: [{ ... required: true }, ...]
标志 - 但我不确定如何将包含在中以查询但不包含要求它的结果采集。
在我的梦想世界中,续集查询看起来像
db.Post.findAll({ where: { photo: { $eq: null }, audio: ... } })
答案 0 :(得分:1)
使用required: false
生成左外部联接。
const lonelyPosts = await db.Post.findAll({
include: [
{ model: db.Photo, required: false, attributes: [] },
{ model: db.Audio, required: false, attributes: [] },
],
where: [
Sequelize.where(Sequelize.col('photo.id'), null),
Sequelize.where(Sequelize.col('audio.id'), null),
],
})
答案 1 :(得分:0)
尝试不包含
db.Post.findAll({
where: {
'$photo.id$': { $eq: null },
'$audio.id$': { $eq: null }
},
order: [
['createdAt', 'DESC']
]
}).then((posts) => {
...
});