sequelize.js - Sequelize.js 如何获取 'INCLUDE' 子句内的记录计数

标签 sequelize.js

根据文档,sequulize 有一种方法可以像这样获取记录计数,

Project.count().then(c => {
  console.log("There are " + c + " projects!")
})

但就我而言,我想获取 include 子句中的记录计数。

我有两张 table 。

  1. 项目
  2. 评分

一个项目有多个评分。

评级属于某个项目。

此查询将输出项目以及评级。

const dataSet = await db.restaurant_items.findAll({
raw: true,
include: [{
                model: db.ratings,
                as: 'rates',
        }]
})

但我想说的是,项目 A 有 10 个评分,项目 B 有 25 个这样的评分

如何实现这一目标?

最佳答案

通过包含,你可以这样做:

db.restaurant_items.findAll({
raw: true,
    include: [{
        model: db.ratings,
        as: 'rates',
        attributes : [ 
                        'project_id' ,  // <-- Reference key to parent table
                        [Sequelize.fn("COUNT", Sequelize.col("data_id")), "historyModelCount"] 
                    ],
        separate:true, // <---- Magic is here
        limit : 1 
    }]
})

关于sequelize.js - Sequelize.js 如何获取 'INCLUDE' 子句内的记录计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52184104/

相关文章:

javascript - Sequelize : how to get flattened data, 基于嵌套关联加入表时?

node.js - Sequelize nodejs 包含模型属性名称别名

mysql - Sequelize Js - 如果不存在则创建新数据库

javascript - 对 Sequelize 中的链式 promise 使用 then promise 时 undefined object

node.js - Sequelize CLI : db:migrate results in most columns failing to add

node.js - 使用 sequelize 在 nodejs 和 Postgres 中插入时出错

javascript - 将模型 Sequelize 为空/空

javascript - Sequelize : updating updatedAt manually

javascript - Sequelize : multiple belongsTo and hasMany issue

node.js - 为什么我的 Model.find 什么也没返回?