Reputation: 5
please tell me how to get the total number of elements of the nested sequelize model? It is necessary for include to return, in addition to the array of all nested models, also count (the number of all nested models) I would be grateful for the answer
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']],
},
],
})
Upvotes: 0
Views: 79
Reputation: 2095
products = await Product.findAndCountAll({
include: [
{
model: ProductVariant,
as: 'variant',
attributes:[[sequelize.fn('count', sequelize.col('model')), 'TotalNumberOfModels']
},
],
})
Upvotes: 1