我有三个模型,看起来像这样:
const Reagent = sequelize.define('reagent', {
name: {
type: DataTypes.STRING,
allowNull: false,
},
...
})
const Box = sequelize.define('box', {
code: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
quantity: {
type: DataTypes.INTEGER,
allowNull: false,
},
...
})
const BoxActivity = sequelize.define('boxActivity', {
quantity: {
type: DataTypes.INTEGER,
allowNull: false,
},
date: {
type: DataTypes.Date,
allowNull: false,
}
})
Reagent.hasMany(Box);
Box.belongsTo(Reagent);
BoxActivity.belongsTo(Box);
Box.hasMany(BoxActivity);
我想获取带有数量总和的试剂列表(来自BoxActivity的
quantity
)模型,但我不知道如何实现这一点。
我写过这个:
await BoxActivity.findAll({
attributes: ['boxId', [sequelize.fn('SUM', sequelize.col('quantity')), 'totalQuantity']],
group: ['boxId'], // I need it grouped by reagent not box.
where: {
quantity: {
[Op.gt]: 0
}
}
})
接下来我可以尝试什么?
您需要在架构中定义外键引用,然后在查询中您可以像这样包含它们
modelA.findAll({
include:[
{model:modelB,attributes:[]},
{model:modelC,attributes:[]}
],
attributes:[
//here you can access and manipulate modelB and modelC's columns
// like this sequelize.col('"modelB"."id"') and even use them in
//group by or order by
]
})