[英]sequelize - get AVG of included model
我有一个类似于product: { ... ,ratings: [ {rating: 3} ] }
架构,并使用sequalize,我想使用sequelize
添加属性product.avg_rating
。
这是我的代码 :
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=>{...})
但我不断收到此错误 :
在没有GROUP BY的聚合查询中,SELECT列表的表达式#1包含非聚合列'text_rewriter.languageCombination.id'; 这与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,等级,product_id
在上述情况下,关系将为“ rating.belongsTo(product)或product.hasMay(rating)”
MySQL实现对功能依赖性的检测。 如果启用了ONLY_FULL_GROUP_BY SQL
模式(默认情况下),则MySQL拒绝查询,其中选择列表, HAVING
条件或ORDER BY
列表引用的是未聚合的列,这些列既未在GROUP BY
子句中命名,也未在功能上依赖在他们。
该错误与sql_mode
有关,您需要在数据库控制台上执行以下命令。
SET GLOBAL sql_mode = '';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.