根据文档,sequulize 有一种方法可以像这样获取记录计数,
Project.count().then(c => {
console.log("There are " + c + " projects!")
})
但就我而言,我想获取 include
子句中的记录计数。
我有两张 table 。
- 项目
- 评分
一个项目有多个评分。
评级属于某个项目。
此查询将输出项目以及评级。
const dataSet = await db.restaurant_items.findAll({
raw: true,
include: [{
model: db.ratings,
as: 'rates',
}]
})
但我想说的是,项目 A 有 10 个评分,项目 B 有 25 个这样的评分
如何实现这一目标?
最佳答案
通过包含,你可以这样做:
db.restaurant_items.findAll({
raw: true,
include: [{
model: db.ratings,
as: 'rates',
attributes : [
'project_id' , // <-- Reference key to parent table
[Sequelize.fn("COUNT", Sequelize.col("data_id")), "historyModelCount"]
],
separate:true, // <---- Magic is here
limit : 1
}]
})
关于sequelize.js - Sequelize.js 如何获取 'INCLUDE' 子句内的记录计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52184104/