首页 > 解决方案 > 如何获得嵌套续集模型的元素总数?

问题描述

请告诉我如何获得嵌套续集模型的元素总数?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']],
          },
        ],
      })

标签: postgresqlormsequelize.js

解决方案


products = await Product.findAndCountAll({
        include: [
          {
            model: ProductVariant,
            as: 'variant',
            attributes:[[sequelize.fn('count', sequelize.col('model')), 'TotalNumberOfModels']
          },
        ],
      })

推荐阅读