首页 > 解决方案 > Sequelize group by include 模型在 MySQL 中工作正确,但在 SQL Server 中出现“列...在选择列表中无效...”错误

问题描述

Sequelize group by include 模型在 MySQL 中可以正常工作,但在 SQL Server 中不能正常工作,核心代码如下

楷模

var topics = sequelize.define('topics', {
        id: {
            type: DataTypes.INTEGER,
            primaryKey: true,
            allowNull: false,
            autoIncrement: true
        },
        title:{
            type:  DataTypes.STRING,
            allowNull: false
        }
});
var comment = sequelize.define('comment', {
        id: {
            type: DataTypes.INTEGER,
            primaryKey: true,
            allowNull: false,
            autoIncrement: true
        },
        text: { type:DataTypes.TEXT, allowNull:false },
        topic_id: { type: DataTypes.INTEGER, allowNull:false }
});

// Association
comment.hasOne(topics, {foreignKey:"id", sourceKey:"topic_id"})
topics.hasMany(comment, { foreignKey:"topic_id", sourceKey:"id" })

// Query get error in SQL Server, but goes well in MySQL
topics.findAll({
        group:["topics.id"],
        include: [{ model:comment, attributes:[] }]
})

上面的代码在 mySQL 中运行良好,但在 SQL Server 中运行时,出现错误“Column 'topics.id' is invalid in the selected list....”

标签: node.jssql-serversequelize.js

解决方案


我已经解决了这个问题,在 MSSQL 中,诀窍是您需要列出组中的所有字段,如下所示:

topics.findAll({
   group:["topics.id","topics.title"], // <---- need to list "topics.title"
   include: [{ model:comment, attributes:[] }],
   attributes:{
      include:[[sequelize.fn('count',sequelize.col('comments.id')),'participants']]
   }
})

推荐阅读