Node.js - Sequelize.js嵌套关联检查外部条件 - 未定义

时间:2018-02-12 07:54:46

标签: node.js associations sequelize.js where-clause nested-query

使用Sequelize版本实现:“^ 4.15.0”

我正在尝试从包含关联的2级添加where条件。

Model1.find({
    include: [
       {
           model: Model2,
           as: 'model2_alias',
           attributes: [
               'model2_id'
           ],
           include: [{
               model: Model3,
               as: 'model3_alias',
               attributes: [
                   'model3_id'
               ]
           }]
       }
    ],
    where: {
        model3_alias.id: { [Op.in]: [1, 2, 3] }
    }
});

我已经厌倦了这个方法:

where: {
    '$model2_alias.model3_alias.id$': { [Op.in]: [1, 2, 3] }
}

但是给出了model2_alias.model3_alias.id未定义/未找到的错误。

上述内容在写为'$model2_alias.id$': { [Op.in]: [1, 2, 3] }时确实有效,因此语法必须写入,但如何再降低一级。

在任何MySQL管理工具中执行形成的SQL语句时,会给出正确的结果,因此我尝试实现的where条件也没有错。

任何想法我在这里缺少什么或者这只适用于一个级别。然后该怎么做更多级别?

3 个答案:

答案 0 :(得分:3)

你可以在任何级别添加这样的地方 -

Model.find({
    where : { 
    // where 1
    },
    include : [{
        model : Model1,
        where : {
        // Where 2
        },
        include : [{
            model : Model2,
            where : {
            // Where 3
            }
        }]
    }]

});

希望有所帮助!

答案 1 :(得分:0)

我认为您的代码无效,因为您使用的是model1_id而不是id。所以代码应该是

Model1.find({
    include: [
       {
           model: Model2,
           as: 'model2_alias',
           attributes: [
               'id'
           ],
           include: [{
               model: Model3,
               as: 'model3_alias',
               attributes: [
                   'id'
               ]
           }]
       }
    ],
    where: {
        '$model2_alias.model3_alias.id$': { [Op.in]: [1, 2, 3] }
    }
});

同样@Rahul提到,你可以直接在你的包内使用

Model1.find({
    include: [
       {
           model: Model2,
           as: 'model2_alias',
           attributes: [
               'id'
           ],
           include: [{
               model: Model3,
               where: {
                  'id': { [Op.in]: [1, 2, 3] }
               }
               as: 'model3_alias',
               attributes: [
                   'id'
               ]
           }]
       }
    ],
});

答案 2 :(得分:0)

另外,你可以尝试

sequelize.where()

e.g。

sequelize.where(
      sequelize.literal('"model2_alias.model3_alias.id"'), { [Op.in]: [1, 2, 3] }
    )

关于sub query,表示您使用limit / offset +(1:m关系或left join}。 如果您有1:1关系,只需将required: true添加到include,即可获得inner join而不是left joinsequelize不会创建sub query System.currentTimeMillis