4 ms·
I don't know about active record but with Django it's simply: Post.objects.all().annotate(Count('comments')) Which produces (simplified, Django would actual
by samwillis 10y ago
I don't know about active record but with Django it's simply:
Post.objects.all().annotate(Count('comments'))
Which produces (simplified, Django would actually explicitly select each column):
SELECT posts.*, COUNT(comments.id) AS comments_count
FROM posts
LEFT OUTER JOIN comments ON (posts.id = comments.post_id) GROUP BY posts.id
Nice, easy and without 1+N queries.
- sirn 10y agoThat is actually very nice and elegant!