sequelize.js - Sequlize.js how to get the records count inside an 'INCLUDE' clause
问题描述
According to the documentation sequlize has a way to get the records count like this,
Project.count().then(c => {
console.log("There are " + c + " projects!")
})
But in my case I want to get records counts inside the include
clause.
I have two tables.
- items
- ratings
A item has many ratings.
A rating is belongs to an item.
This query will out put the items along with the ratings.
const dataSet = await db.restaurant_items.findAll({
raw: true,
include: [{
model: db.ratings,
as: 'rates',
}]
})
But what I want is to say Item A has 10 ratings, Item B has 25 ratings like that
How do I achieve this?
解决方案
使用 include 你可以这样做:
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
}]
})
推荐阅读
- css - bootstrap 4 css 在卡片右下角显示包含文本的黄色三角形,是 css 的方式吗?
- python-3.x - 如何将文件保存到目录并将这些文件附加到 Python 中的列表中?
- c - while ( *(mychar++)) 什么时候停止
- android - 任务“:app:mergeExtDexXXXDebug”执行失败
- javascript - 收到第二个控制器未注册的错误
- javascript - JavaScript 不会阻止音频播放器的默认功能
- android - 迁移到 New Places SDK 客户端找不到符号变量 PLACE_DETECTION_API
- javascript - 使用 deepEqual 比较数组时出错。我的错误是什么,为什么?
- sql - 如何在雪花中查找非 utf8 字符的行?
- flutter - 如何在颤动中创建这样的交错网格视图