node.js - 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....”
解决方案
我已经解决了这个问题,在 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']]
}
})
推荐阅读
- sql - 将 nvarchar 值“”转换为数据类型 int 时 SQL Server 数据库错误转换失败
- powershell - PowerShell 为 cmdlet 实现 -AsJob
- php - 如何使用 PHP 根据下拉列表中的选择从数据库中获取数据?
- command - “代码”不是内部或外部命令、可运行程序或批处理文件
- reactjs - 将 React 应用程序转换为 PWD 后,网址发生了变化
- python - 根据另一个数组中指示的位置提取数组
- javascript - 如何在网络面板中部署 node.js 应用程序?
- c++ - 检查链表是否为回文
- javascript - 在javascript中使用双反斜杠解析json
- php - 如何在 PHP 中重置数组键