Sequelize ORM中连接表的条件

时间:2016-03-28 13:00:35

标签: javascript sql postgresql orm sequelize.js

我希望通过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是否可以进行第一次查询,或者我应该坚持原始查询?

2 个答案:

答案 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
       }
   }