Sequelize where condition 用于包含的模型

Sequelize where condition used for included model

我有两个关联的模型 -> 订单属于阶段,我想在选择具有所选 phase.projectId 的订单时使用 where 子句。

models.Order.findAll( {
        attributes:[
            'id',
            'product_id',
            'phase_id',
            [models.Order.sequelize.fn('sum', models.Order.sequelize.col('invoiced')), 'invoiced_quantity'],
        ],
        include: [{model:models.Phase, as:'phase', required: true}],
        where:{'$phase.projectId$': chosenProject.id},
        group:[
            'product_id'
        ],
        raw: true
    })

但它会在 'where clause'

中创建错误未知列 'phase.projectId'

是否可以对包含的模型使用 where 子句?

您可以在 include 中使用 where 子句。

models.Order.findAll( {
        attributes:[
            'id',
            'product_id',
            'phase_id',
            [models.Order.sequelize.fn('sum', models.Order.sequelize.col('invoiced')), 'invoiced_quantity'],
        ],
        include: [{model:models.Phase, as:'phase', where: {id: chosenProject.id}],
        group:[
            'product_id'
        ],
        raw: true
    })

并且包含make inner join中的where子句(w/o required: true选项)。