javascript - sequelize - 获取包含模型的 AVG

标签 javascript mysql node.js sequelize.js

我有一个类似于 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/

相关文章:

javascript - 遍历嵌套在对象中的数组以查找匹配项

javascript - NodeJS 中是否有任何简单的方法可以将多部分/表单数据转换为数组?

php - 如何在 PHP 中多次在 SQL 查询中漫游

mysql - 选择timestampdiff超过1天并且有一些null的地方

javascript - 如何在javascript中 trim 末尾不需要的连续字符串?

JavaScript (Node.js) : app. 设置 ('port' ,端口); ^ TypeError : app. set 不是一个函数

javascript - ! JavaScript 中的运算符

javascript - 如何使用 Jquery 向下滑动添加到 DOM 之前隐藏的元素?

javascript嵌套类型对象到json并返回

php - MySQL比较具有时差的日期