难以将sql查询转换为sequelize查询

时间:2019-01-24 12:12:46

标签: postgresql sequelize.js aggregate-functions

我很难在续集中实现此查询。 出现以下错误

 Tried to select attributes using Sequelize.cast or Sequelize.fn 
 without specifying an alias for the result, during eager loading.
 This means the attribute will not be added to the returned instance

SQL查询:

SELECT a.id,a.name,a.color,COALESCE(COUNT(b.group_id), 0) as studentCount
FROM students_groups as a
INNER JOIN students_groups_mapping as b ON a.id = b.group_id where a.archive = false
GROUP BY a.id
ORDER BY a.name

协会:

db.studentsGroupsMapping.belongsTo(db.studentGroups,{
  foreignKey : 'group_id',
  targetKey :  'id',
  as : 'studentsGroupsMapping'
});
db.studentGroups.hasMany(db.studentsGroupsMapping,{
  foreignKey : 'group_id',
  targetKey : 'id',
  as : 'studentsGroupsMapping'
});

序列化查询:

   studentGroups.findAll({
        where : {archive : false},
        attributes : ['id','name','color'],
        include : [{
            model : studentsGroupsMapping,
            as : 'studentsGroupsMapping',
            attributes : [sequelize.fn('count',sequelize.col('studentsGroupsMapping.group_id')),'studentsCount'],
            required : true
        }]
    }).then((data)=>{
        res.send(data)
    });

0 个答案:

没有答案