Where condition for joined table in Sequelize ORM(Sequelize ORM中连接表的条件)
问题描述
我想用 sequelize ORM 得到这样的查询:
I want to get query like this with 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')
问题是续集不允许我在 where 子句中引用B"或C"表.以下代码
The problem is that sequelise not letting me to reference "B" or "C" table in where clause. Following code
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
这是完全不同的查询,结果是
which is completely different query, and result of
A.findAll({
where: {
$or: [
{'"B"."userId"' : 100},
{'"C"."userId"' : 100}
]
},
include: [{
model: B,
required: false
}, {
model: C,
required: false
}]
]
甚至不是一个有效的查询:
is no even a valid query:
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 是否可以进行第一次查询,或者我应该坚持原始查询?
Is first query even possible with sequelize, or I should just stick to raw queries?
推荐答案
将引用连接表的列包装在 $$
Wrap the columns which reference joined tables in $$
A.findAll({
where: {
$or: [
{'$B.userId$' : 100},
{'$C.userId$' : 100}
]
},
include: [{
model: B,
required: false
}, {
model: C,
required: false
}]
});
这篇关于Sequelize ORM中连接表的条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Sequelize ORM中连接表的条件
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Fetch API 如何获取响应体? 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01