我想用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”表。以下代码
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是否可以进行第一个查询,还是我应该坚持使用原始查询?
将引用联接表的列包装在 $$
$$
A.findAll({ where: { $or: [ {'$B.userId$' : 100}, {'$C.userId$' : 100} ] }, include: [{ model: B, required: false }, { model: C, required: false }] });