javascript - 需要计算一个连接表行sequelize
问题描述
我sequelize
用来查询sqlserver
数据库。我有两张桌子:
data: columns - id, name, team, type
history:columns - id, node, date, status, data_id(foreignkey)
和一个关系
history.belongsTo(data, {foreignKey: 'data_id'}
data.hasMany(history, {foreignKey: 'data_id'})
我的查询是:
dataModel.findAll({
attributes: ['name'],
include: [{
model:historyModel
}]
})
我的结果如下所示:
[
{
name: "1",
history: [
{
...
}
]
},
{
name: "2",
history: [
{
...
}
]
}
]`
我希望用它而不是历史数组来计算每个历史对象的数量。中的查询sql
是:
select data.name, count(history.data_id) count
from history
inner join data on data.id=history.data_id
group by history.data_id, data.name
解决方案
你可以这样做:
dataModel.findAll({
attributes: {
include: [[Sequelize.fn("COUNT", Sequelize.col("history.data_id")), "historyModelCount"]]
},
include: [{
model: historyModel, attributes: []
}],
group: ['data.id']
});
推荐阅读
- node.js - 在 Facebook `og:image` 标签中使用 Google Cloud Storage 的公共 URL
- wpf - 在 Powershell 中运行的 XAML 文本框中捕获 Enter 键
- excel - 通过在 X&Y 范围内给出 X 值来计算 Y 轴值
- python - 尝试将列表导入 mysql 表时出错
- javascript - 按组将 2 列合并为 1 列
- ios - 在 Xcode 的右侧窗口中逐行查找代码的输出,但它不存在
- angular - 使用 Angular 7 组件在页面刷新时构建面包屑
- woocommerce - 如果自定义结帐字段中有值,如何将购物车总数归零?
- javascript - 如何访问不同组件中的商店?
- r - 闪亮的服务器找不到闪亮的默认css和js文件