我有一个类似于 product: { ... ,ratings: [ {rating: 3} ] }
的模式,并且使用 sequalize,我想添加一个属性 product.avg_rating
使用 sequelize
。
这是我的代码:
sequelize.models.product.findAll({
include: [{
model: sequelize.models.rating,
as: 'ratings',
attributes: {
include: ['rating',[sequelize.fn('AVG', 'ratings.rating'), 'avg_rating']]
},
group: ['rating.rating'],//also tried ratings.rating, and just rating
}],
}).then(products=>{...})
但我一直收到这个错误:
In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column 'text_rewriter.languageCombination.id'; this is incompatible with sql_mode=only_full_group_by
目标输出:
products: [
{product: 'product name',
...
ratings: [...],
avg_rating: 3.7 //THIS AVG IS WHAT I WANT
},{...}
]
有什么想法我想念的吗?我看过很多例子,但没有一个像我那样使用我发现的 include。
最佳答案
sequelize.models.product.findAll({
include: [{
model: sequelize.models.rating,
as: 'ratings',
attributes: ['avg_rating'] //this is column name here
}],
}).then(products=>{...})
这将返回:-
products: [
{product: 'product name',
ratings: [...],
rating : { //here all the attributes you wanted, in this case only 'avg_rating' }
},
{...}
]
但是你必须在使用这个之前定义产品表和评级表之间的关系。
表:产品有id,名称
表:评分有id、rating、product_id
在上述情况下,关系将是“rating.belongsTo(product) OR product.hasMay(rating)”
关于javascript - sequelize - 获取包含模型的 AVG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49461912/