question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Ordering by the COUNT of a relation

See original GitHub issue

Issue type:

[x] question [ ] bug report [ ] feature request [ ] documentation issue

Database system/driver:

[ ] cordova [ ] mongodb [ ] mssql [x] mysql / mariadb [ ] oracle [ ] postgres [ ] cockroachdb [ ] sqlite [ ] sqljs [ ] react-native [ ] expo

TypeORM version:

[x] latest [ ] @next [ ] 0.x.x (or put your version here)

Steps to reproduce or a small repository showing the problem:

I’m a bit confused by how to order my data by the COUNT of a relation. If I have a post with likes:

@Entity()
class Post {
  @OneToMany('PlaceLike', 'place', { cascade: true, eager: true })
  likes: PlaceLike[]
}

How do I ORDER BY the number of Likes a Post has? There seems to be a few undocumented/deprecated ways like @RelationCount and loadRelationCountAndMap but they don’t really work. Any ideas?

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:2
  • Comments:8

github_iconTop GitHub Comments

10reactions
pincmancommented, Nov 11, 2020

@sekaru just

this.createQueryBuilder('a')
                .select('a.id')
                .addSelect((subQuery) => {
                    return subQuery
                        .select('COUNT(c.id)', 'count')
                        .from(Comment, 'c')
                        .where('c.article.id = a.id');
                }, 'count')
                .orderBy('count', 'DESC')
                .loadRelationCountAndMap('a.comment_count', 'a.comments')

both has orderBy and Count

3reactions
aboveyunhaicommented, Jun 18, 2021

@sekaru just

this.createQueryBuilder('a')
                .select('a.id')
                .addSelect((subQuery) => {
                    return subQuery
                        .select('COUNT(c.id)', 'count')
                        .from(Comment, 'c')
                        .where('c.article.id = a.id');
                }, 'count')
                .orderBy('count', 'DESC')
                .loadRelationCountAndMap('a.comment_count', 'a.comments')

both has orderBy and Count

wouldn’t this cause querying Comment twice unnecessarily ? one from addSelect and one from load relation? I felt like it may cause performance issue. Correct me if I’m wrong.

Also it seems like there is a terrible bug with typeORM for postgresql .orderBy('count', 'DESC') may cause column does not exist, instead use

.orderBy(`"count"`, 'DESC)`  OR .orderBy('"count"', 'DESC')

It’s extremely frustrating after I check the raw query.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Laravel OrderBy relationship count - Stack Overflow
I'm trying to get the most popular hackathons which requires ordering by the respective hackathon's partipants->count() . Sorry if that's a little difficult ......
Read more >
Order by relationship count - Laracasts
Order by relationship count ... You can this as a cleaner way to sort by vote count: ... But I don't know what...
Read more >
Examples of SQL Order by Count - eduCBA
ORDER BY COUNT clause in standard query language(SQL) is used to sort the result set produced by a SELECT query in an ascending...
Read more >
Order By Relationship Count - Laravel - Pine
Let's say we have a Post model and a Comment model. The Comment model has a belongsTo() relationship with the Post, while the...
Read more >
Relation field count & ordering by relation count - Database-SQL
Even in v4, there's no count metadata for relation fields. So what's the best approach to be able to easily: get number of...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found