简体   繁体   中英

sequelize - get AVG of included model

I have aa schema that is like product: { ... ,ratings: [ {rating: 3} ] } , and using sequalize, I would like to add on a property product.avg_rating using sequelize .

Here is my code :

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=>{...})

But I keep getting this error :

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

Goal Output:

products: [
   {product: 'product name',
    ...
    ratings: [...],
    avg_rating: 3.7 //THIS AVG IS WHAT I WANT
   },{...}
]

any ideas what I am missing? I have seen many examples, but none of them use include like I did that I found.

sequelize.models.product.findAll({
include: [{
   model: sequelize.models.rating,
   as: 'ratings', 
   attributes:  ['avg_rating'] //this is column name here
}],
}).then(products=>{...})

This will return :-

products: [
 {product: 'product name',
 ratings: [...],
 rating : { //here all the attributes you wanted, in this case only 'avg_rating' }
 },
 {...}
]

But you have to define relastionship between products table and rating table before using this.

Table : Product have id, name

Table : Rating have id, rating, product_id

In above case relationship will be 'rating.belongsTo(product) OR product.hasMay(rating)'

MySQL implements detection of functional dependence. If the ONLY_FULL_GROUP_BY SQL mode is enabled (which it is by default), MySQL rejects queries for which the select list, HAVING condition, or ORDER BY list refer to non-aggregated columns that are neither named in the GROUP BY clause nor are functionally dependent on them.

The error is related to sql_mode , you need to execute the following command on your database console.

SET GLOBAL sql_mode = '';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM