对包含模型使用的条件进行序列化
我有两个关联的模型->订单属于阶段,我想在选择具有所选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
})
但它会创建错误 Unknown columns 'phase.projectId' in 'where Clause'
是否可以对包含的模型使用 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
})
以及 include 中的 where 子句进行内部联接(不包含
required: true
选项)。