簡體   English   中英

sequelize-獲得包含模型的AVG

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM