我正在尝试使用 sequelize 获得模型“用户”的关联模型“评级”的平均评级。
sequelize.sync({logging: false}).then(()=>{
return Model.Rating.findAll({
attributes: [[Sequelize.fn('avg', Sequelize.col('stars')),'rating']]
})
}).then(res => {
res = res.map(r => r.get())
console.log(res);
})
Run Code Online (Sandbox Code Playgroud)
直接从“评级”模型尝试时,我得到了正确的响应:
[ { rating: '3.5000000000000000' } ]
Run Code Online (Sandbox Code Playgroud)
但是,当尝试通过“用户”的关联执行相同操作时,我会得到单独的值而不是平均值。
sequelize.sync({logging: false}).then(()=>{
return Model.User.findOne({
where: {id: 7},
include : [{
model: Model.Rating, as: 'seller_rating',
attributes: [[Sequelize.fn('avg', Sequelize.col('stars')),'rating']]
}],
attributes: {
exclude: ['password']
},
group: ['seller_rating.id', 'user.id'],
})
}).then(res => {
res = res.get()
res.seller_rating = res.seller_rating.map(r => r.get())
console.log(res)
})
Run Code Online (Sandbox Code Playgroud)
我不得不在组中添加“seller_rating.id”和“user.id”,否则 sequelize 会抛出错误。
{
id: 7,
email: 'example@gmail.com',
createdAt: 2020-01-20T09:07:47.101Z,
updatedAt: …Run Code Online (Sandbox Code Playgroud)