简体   繁体   English

按计数关联顺序排列?

[英]Sequelize order by count association?

I have User and Post table.我有UserPost表。 User has Many Posts relationship. User has Many Posts关系。 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?我如何编写这个 sequelize 查询?

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?如何让这个用户查询按 Post 排序?

There is probably a better way, but you can use a .literal() to create a subquery and assign an alias.可能有更好的方法,但您可以使用.literal()创建子查询并分配别名。 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:这将产生以下 SQL:

SELECT 
    `User`.`username`, 
    (SELECT COUNT(*) FROM Posts WHERE Posts.userId = User.id) AS `PostCount` 
FROM 
    `Users` AS `User` 
ORDER BY 
    PostCount DESC

sequelize has this, but you need to create an alias for the count sequelize 有这个,但是你需要为计数创建一个别名

User.findAll({
  attributes: {
    include: [
       [sequelize.fn('COUNT', sequelize.col('Post.id')), 'count']
    ]
  },
  include: [{
    attributes: [],
    model:Post,
    duplicating: false,
    required: false
  }],
  group: ['User.id'],
  order: [['count', 'DESC']]
});

Turn it around so that sequelize gives you把它转过来让续集给你

SELECT  u.username,
        COUNT(*) AS PostCount
    FROM Users AS u
    JOIN Posts AS p  ON p.userId = u.userId
    GROUP BY u.userId, u.username
    ORDER BY PostCount DESC

That is, start with Post, not User.也就是说,从 Post 开始,而不是 User。

May be this can work可能这可以工作

var User = objAllTables.User.User();
var Post = objAllTables.Post.Post();

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


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

            User.findAndCountAll({
                attributes: ['User.username'],
                include: [{ model: Post }]
            }).then(function (result) {
                 console.log(result.count);
                 console.log(result.rows);
            })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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