postgresql - 如何获得包括模型 Sequelize 的总数?
问题描述
请告诉我如何获取嵌套表中所有元素的计数?为什么 variantCount 不正确?必须是 5,但我只得到 1。
我将非常感谢您的帮助
products = await Product.findAll({
attributes: ['name', [Sequelize.fn('COUNT', 'variant.id'), 'variantCount']],
include: [{ model: ProductVariant, as: 'variant', attributes: ['title', 'img'] }],
group: ['product.id', 'variant.id'],
})
输出:`
[
{
"name": "nike-metcon-7",
"variantCount": "1",
"variant": [
{
"title": "Nike Metcon 7 (Grey)",
"img": "f7b6faf0-0522-4443-83c5-3ceeebc54453.jpg"
},
{
"title": "Nike Metcon 7 (Blue)",
"img": "e8d105a3-2704-4d08-97d7-7382fdb940b1.jpg"
},
{
"title": "Nike Metcon 7 (White)",
"img": "66c01ec6-ec09-4dec-be24-5164358440ed.jpg"
},
{
"title": "Nike Metcon 7 (Grey)",
"img": "b0c72280-e116-479c-a3c2-f323b462a861.jpg"
},
{
"title": "Nike Metcon 7 (Red)",
"img": "c93a50fe-14a5-4e0f-a5d1-014bc45dc3c9.jpg"
}
]
},
]
`
解决方案
尝试子查询确切的输出,这比从左连接表中提取计数要简洁
products = await Product.findAll({
attributes: ['name', [Sequelize.literal('(select count(variant.id) from ProductVariant where product.variant_id = variant.variant_id)'), 'variantCount']],
include: [{ model: ProductVariant, as: 'variant', attributes: ['title', 'img'] }],
group: ['product.id', 'variant.id'],
})
推荐阅读
- google-bigquery - 为什么 BigQuery 在保存表时会耗尽内存,而不是对于不保存的相同查询?
- keycloak - 尝试在两个 Keycloak 之间联合用户时出现意外错误(来自令牌的错误受众)
- python - 列表中的重复字符串不会被删除,除非最相似的字符串在子列表中
- openssl - 将普通公钥转换为 PEM
- java - 在项目中添加 Java 代码模板 XML 文件
- sql - 如何强制生成新的 sysdatetime()?
- authentication - 如何使用 Postman 创建 oAuth 随机数、时间戳和签名?
- c# - 为什么 jquery datable 显示旧记录而不是新记录?
- powershell - 如何快速更改 shell 文件夹以匹配当前打开的文件
- angular - NumbersOnly 指令 - 检测复制和粘贴键盘组合