【问题标题】:Find Count From Other Table in Sequelize在 Sequelize 中从其他表中查找计数
【发布时间】: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


    【解决方案1】:

    您可以使用attributesinclude 来获取您的类别以及与之相关的产品数量

    Category.findAll({
            attributes: {
              include: [
                [
                  Sequelize.fn('COUNT', Sequelize.col('products.categoryRef')),
                  'productsCount'
                ]
              ]
            },
            include: [
              {
                model: Product,
                attributes: []
              }
            ],
            group: ['id']
          });
    

    【讨论】:

    • 如果您有任何疑问,请告诉我
    • 它给了我这个错误:在没有 GROUP BY 的聚合查询中,SELECT 列表的表达式 #1 包含非聚合列 'inventory.category.id';这与 sql_mode=only_full_group_by 不兼容
    • 感谢兄弟,现在它正在工作。你能告诉我可以学习sequelize的资源吗?
    • 如果您有任何疑问,请告诉我
    • 您好,很抱歉,但问题尚未解决,它给了我“字段列表”中未知列“categoryId”的错误如何指定我们在模型中拥有 categoryRef 的键名而不是 categoryId ?
    猜你喜欢
    • 2021-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-04
    • 2020-11-30
    相关资源
    最近更新 更多