Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize order by count association?

Tags:

I have User and Post table. User has Many Posts relationship. I want to query User and order the query by the number of posts that the users made. How do I write this sequelize query?

Post.belongsTo(User, {foreignKey: 'userId'});
User.hasMany(Post, {foreignKey: 'userId'});

User.findAll( {
  order: 'COUNT(Post) DESC', //???
  include: [Post]
});

How do I get this User query sorted by Post?

like image 285
user4643472 Avatar asked Nov 24 '15 18:11

user4643472


People also ask

How do you order by in Sequelize?

To add an ORDER BY clause to the Sequelize query methods, you need to specify the order option inside the query methods you used for retrieving data from your database. Now you are tasked with retrieving the data from the table, ordering the result with the following rules: Sort by population column in descending order.

How do you use count in Sequelize?

Sequelize Model. count() method is used to generate and execute a SELECT COUNT SQL query to your connected database. The method accepts an object of options that you can define to modify the generated query. You need to create a Sequelize Model for the above table and call the count() method from there.

What is findByPk?

findByPk ​ The findByPk method obtains only a single entry from the table, using the provided primary key. const project = await Project. findByPk(123); if (project === null) {

Why we use raw true in Sequelize?

The Sequelize setters and getters might not be used here. So setting raw to true provides me the desired output with a cleaner look & feel.


1 Answers

There is probably a better way, but you can use a .literal() to create a subquery and assign an alias. Then, you can reference the alias when ordering, sample:

User.findAll({
    attributes: [
        'User.username',
        [sequelize.literal('(SELECT COUNT(*) FROM Posts WHERE Posts.userId = User.id)'), 'PostCount']
    ],
    order: [[sequelize.literal('PostCount'), 'DESC']]
});

This would produce the following SQL:

SELECT 
    `User`.`username`, 
    (SELECT COUNT(*) FROM Posts WHERE Posts.userId = User.id) AS `PostCount` 
FROM 
    `Users` AS `User` 
ORDER BY 
    PostCount DESC
like image 188
alecxe Avatar answered Sep 18 '22 17:09

alecxe