我有两个续集模型,我们称它们为
A
和B
。 A
有多个 B
,并且 B
可以属于多个 A
。我想找到 A
的所有实例,这些实例具有与其关联的模型 B
,其中 B.id == 'some string
。但是,在 A.findAll
的结果中,我希望返回的每个 A
都包含所有关联的 B
,无论是否 B.id == 'some string
。
A.findAll({
where: {'$B.id$':'some string'},
include: [{model:B, through: {attributes: []}},{model:C, required:true}]
})
但这会导致错误,因为它在子查询期间没有加入
B
。请参阅下面的伪 SQL 示例
SELECT *
FROM (
SELECT *
FROM A
INNER JOIN C ON A.cId = C.id
WHERE B.id = 'some string'//this is the problem
) as A
LEFT OUTER JOIN (
SELECT *
FROM B
INNER JOIN "AtoB" ON "AtoB".bId = B.id
) as Bs ON Bs.aId = A.id
如果我尝试:
A.findAll({
include: [{model:B, through: {attributes: []}, where:{id:'some string'}},{model:C, required:true}]
})
然后正如我所期望的,它只会检索
B
所在的位置 id == 'some string'
。
我正在寻找一种解决方案,可以查找具有关联的
A
(其中 B
)的 B.id == 'some string'
的所有实例,但我希望 findAll 返回的结果集包含与 B
关联的 A
的所有实例.
输出 SQL 类似于:
SELECT *
FROM (
SELECT *
FROM A
INNER JOIN C ON A.cId = C.id
INNER JOIN "AtoB" ON "AtoB".aId = A.id
INNER JOIN B ON B.id = "AtoB".bId
WHERE B.id = 'some string'//this is the problem
) as A
LEFT OUTER JOIN (
SELECT *
FROM B
INNER JOIN "AtoB" ON "AtoB".bId = B.id
) as Bs ON Bs.aId = A.id
你好吗? 经过一番研究后我发现了这一点。您可以在 B 查询中使用包含子句和
required: true
,以确保每个 A 元素都有一个满足您需要的 B。
A.findAll({
include: [{
model: B,
where: {
id: 'some string' // Filter condition for B
},
required: true // This ensures that only A instances with associated B's satisfying the condition are returned
}]
})
希望对您有帮助,试用后告诉我是否有用。