【发布时间】:2020-05-15 16:46:54
【问题描述】:
我在使用 node js 进行续集时遇到问题。我想要按类别计算产品数量。
我的类别模型定义为:
const Sequelize = require('sequelize');
const sequelize = require('../configs/db-connection.config');
const Product = require('../models/product.model');
const Category = sequelize.define(
'category',
{
id: {
type: Sequelize.INTEGER,
primaryKey: true,
allowNull: false,
autoIncrement: true
},
name: {
type: Sequelize.STRING,
allowNull: false
},
},
{ timestamps: true }
);
Category.hasMany(Product);
Product.belongsTo(Category);
module.exports = Category;
我的产品型号定义为:
const Sequelize = require('sequelize');
const sequelize = require('../configs/db-connection.config');
const Product = sequelize.define(
'product',
{
id: {
type: Sequelize.INTEGER,
primaryKey: true,
allowNull: false,
autoIncrement: true
},
name: {
type: Sequelize.STRING,
allowNull: false
},
categoryRef: {
type: Sequelize.INTEGER,
allowNull: false,
foreignKey: true,
references: {
model: CATEGORY.TABLE_NAME,
key: 'id'
}
}
},
{ timestamps: true }
);
module.exports = Product;
这里每个类别都作为产品模型中的 foreignKey 连接到产品,如 categoryRef。 让我举个例子,一个类别是设备,其产品将是笔记本电脑、显示器、CPU 等。如果设备有 3 个产品,那么它将返回 3 作为类别计数。 这里数组中的每个对象都代表类别 obj,我想添加一个额外的字段,即类别 obj 中的计数,它会给我存储为产品表中的 foreignKey 的产品计数。
我的预期结果是:
[
{
id: 1,
name: 'Devices',
createdAt: '2020-01-17T12:08:10.000Z',
updatedAt: '2020-01-17T12:11:22.000Z',
count:3
},
{
id: 2,
name: 'appliances',
createdAt: '2020-01-23T07:59:27.000Z',
updatedAt: '2020-01-23T08:12:54.000Z',
count:0
},
{
id: 3,
name: 'furniture',
createdAt: '2020-01-23T08:51:35.000Z',
updatedAt: '2020-01-23T08:51:35.000Z',
count:0
},
];
我已经在数据库上应用了以下 sql 查询,结果完美:
SELECT inventory.categories.*, count(products.categoryRef) as count
from inventory.categories
left join inventory.products
on (inventory.categories.id = inventory.products.categoryRef)
group by
inventory.categories.id
但我不知道如何将其转换为 sequelize 方法。 请帮助我找出解决方案,我需要使用哪些方法来获得所需的输出。 提前致谢。
【问题讨论】:
标签: mysql node.js sequelize.js