我希望通过sequelize ORM获得这样的查询:
SELECT "A".*,
FROM "A"
LEFT OUTER JOIN "B" ON "A"."bId" = "B"."id"
LEFT OUTER JOIN "C" ON "A"."cId" = "C"."id"
WHERE ("B"."userId" = '100'
OR "C"."userId" = '100')
问题是sequelise不让我在where子句中引用“B”或“C”表。以下代码
A.findAll({
include: [{
model: B,
where: {
userId: 100
},
required: false
}, {
model: C,
where: {
userId: 100
},
required: false
}]
]
给了我
SELECT "A".*,
FROM "A"
LEFT OUTER JOIN "B" ON "A"."bId" = "B"."id" AND "B"."userId" = 100
LEFT OUTER JOIN "C" ON "A"."cId" = "C"."id" AND "C"."userId" = 100
这是完全不同的查询和
的结果A.findAll({
where: {
$or: [
{'"B"."userId"' : 100},
{'"C"."userId"' : 100}
]
},
include: [{
model: B,
required: false
}, {
model: C,
required: false
}]
]
甚至不是有效的查询:
SELECT "A".*,
FROM "A"
LEFT OUTER JOIN "B" ON "A"."bId" = "B"."id"
LEFT OUTER JOIN "C" ON "A"."cId" = "C"."id"
WHERE ("A"."B.userId" = '100'
OR "A"."C.userId" = '100')
sequelize是否可以进行第一次查询,或者我应该坚持原始查询?
答案 0 :(得分:41)
在$$
A.findAll({
where: {
$or: [
{'$B.userId$' : 100},
{'$C.userId$' : 100}
]
},
include: [{
model: B,
required: false
}, {
model: C,
required: false
}]
});
答案 1 :(得分:4)
在include中添加where条件,以及加入。
{
model: C,
where: {
id: 1
}
}