postgresql - 如何获得嵌套续集模型的元素总数?
问题描述
请告诉我如何获得嵌套续集模型的元素总数?include必须要返回,除了所有嵌套模型的数组,还要count(所有嵌套模型的个数) 不胜感激
const Product = sequelize.define('product', {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
name: { type: DataTypes.STRING, unique: true, allowNull: false },
})
const ProductVariant = sequelize.define('product_variant', {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
title: { type: DataTypes.STRING, allowNull: false },
img: { type: DataTypes.STRING, allowNull: false },
color: { type: DataTypes.STRING, allowNull: false },
price: { type: DataTypes.INTEGER, allowNull: false },
model: { type: DataTypes.STRING, allowNull: false },
})
Product.hasMany(ProductVariant, { as: 'variant' })
ProductVariant.belongsTo(Product)
products = await Product.findAndCountAll({
include: [
{
model: ProductVariant,
as: 'variant',
limit: 4,
order: [['createdAt', 'DESC']],
},
],
})
解决方案
products = await Product.findAndCountAll({
include: [
{
model: ProductVariant,
as: 'variant',
attributes:[[sequelize.fn('count', sequelize.col('model')), 'TotalNumberOfModels']
},
],
})
推荐阅读
- sample - 从 dokka 文档中排除样本
- dart - 如何在 http 调用中修复奇怪的飞镖错误
- r - 使用 R 为多个中心开发时间序列
- dart - 如何检查用户是否已登录,如果已登录则显示其他屏幕?
- javascript - AngularJS - 如何跨多个目录自动加载 js 控制器以在主模块中注册?
- java - 懒惰实例化 HashMap 失败
- node.js - 即使在调用 sql.close() 后连接错误
- mongodb - 如何在mongodb的一个公共字段上加入两个集合?
- python - Python 请求:requests.get(url).json() 错误
- java - 在初始化之前将对象或字符串传递给控制器