简体   繁体   中英

Node JS Sequelize how to count associations data

I'm using Sequelize as ORM in node JS. In have two taboes. Event and Comment. And I make an association like this: Event has many comments. Now i want to retreive all the events and count the number of comments of each event. For now I do this:

 db.Event.findAndCountAll({limit: limit,offset: offset, include: [ db.Comment], order: 'date DESC'}).

and next return

JSON.stringify(result.rows).

How can I retrun the number of the comments with only one query.

Please Help me.

Thanky you in advance

The "result" you will return is the one passed to the success callback function, right?

db.Event.findAndCountAll(...).success(
    function(result) { // this guy
        console.log(result.count) //this logs the count
    }
)

You can use result.count to get the value

sequelize.query('SELECT * FROM event AS e JOIN comment AS c ON (c.event_id = e.id)').success(function(result) {
 console.log("Total count", result.count)
}).error(function(err) {
 console.error(err)
});

You always can perform a raw SQL query.

sequelize.query('SELECT * FROM event AS e JOIN comment AS c ON (c.event_id = e.id)').success(function(result) {

}).error(function(err) {

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM