【问题标题】:Sequelize join with group bySequelize join with group by
【发布时间】:2014-12-24 23:18:54
【问题描述】:

我想做的最好用一个小例子来说明。

假设我有以下表格:

表格项

  • 身份证
  • 姓名

表格审核

  • 身份证
  • 评分
  • itemId

很明显,一个项目有很多评论。

如何编写返回以下两列的查询:

  • 项目名称 (Item.name)
  • 所有项目评分的总和 (Sequelize.fn('sum', sequelize.col('rating')))

我想使用 ORM。

【问题讨论】:

    标签: node.js orm sequelize.js


    【解决方案1】:

    尝试使用这个:

    Review.belongsTo(Item, {foreignKey:'itemId', as : 'reviews'});
    Item.hasMany(Review, {foreignkey:'id'});
    
    Item.findAll({attributes:[['id', 'id'],['name', 'name'],[Sequelize.fn('SUM', 'rating'), 'total']], include:[{model:Review, as : 'reviews', required:true}], group:['id'], order:[Sequelize.fn('SUM', 'rating'), 'DESC']}).success(function(result){
        // return array;
        // total     -----> result[i].total
        // item name -----> result[i].name
    })
    

    【讨论】:

      猜你喜欢
      • 2014-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多