[英]Sequelize Where Associated Model is Null
我有 3 個模型: Post
、 Photo
和Audio
。
帖子可以有照片或音頻剪輯(或兩者都沒有):
models.Post.hasOne(models.Photo, { as: 'photo' });
models.Post.hasOne(models.Audio, { as: 'audio' });
我試圖選擇那些兩者都沒有的 - 即只是一個文本帖子。 我一直在挖掘,我到達了(從這里獲取信息):
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 }, ...]
標志 - 但我不確定如何將它包含在查詢中,但不需要它用於結果集合。
在我的夢想世界中,sequelize 查詢看起來像
db.Post.findAll({ where: { photo: { $eq: null }, audio: ... } })
使用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),
],
})
嘗試不包含
db.Post.findAll({
where: {
'$photo.id$': { $eq: null },
'$audio.id$': { $eq: null }
},
order: [
['createdAt', 'DESC']
]
}).then((posts) => {
...
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.