首页 > 解决方案 > Sequlize.js how to get the records count inside an 'INCLUDE' clause

问题描述

According to the documentation sequlize has a way to get the records count like this,

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

But in my case I want to get records counts inside the include clause.

I have two tables.

  1. items
  2. ratings

A item has many ratings.

A rating is belongs to an item.

This query will out put the items along with the ratings.

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

But what I want is to say Item A has 10 ratings, Item B has 25 ratings like that

How do I achieve this?

标签: sequelize.js

解决方案


使用 include 你可以这样做:

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 
    }]
})

推荐阅读