Repository navigation
Order by association count #7431
Replies: 1 comment
|
You usually solve this with a SQL-wise it is basically: SELECT collections.*
FROM collections
LEFT JOIN items ON items.collection_id = collections.id
GROUP BY collections.id
ORDER BY COUNT(items.id) DESC
LIMIT ?;In GORM, something like this: var collections []Collection
err := db.Model(&Collection{}).
Select("collections.*, COUNT(items.id) AS items_count").
Joins("LEFT JOIN items ON items.collection_id = collections.id").
Group("collections.id").
Order("items_count DESC").
Limit(n).
Find(&collections).ErrorIf you also want the count back in Go, scan into a DTO/view model instead of plain One portability note: depending on the database, you may need to group by every selected non-aggregated column (or do it via a subquery and then join back). |
|
you can do this with a subquery count in your order clause. gorm lets you sort by a raw expression: var top []Collection
db.Order("(SELECT COUNT(*) FROM items WHERE items.collection_id = collections.id) DESC").
Limit(10).
Find(&top)if you'd rather do it with a join and group by (handy if you also want the count back), use a struct with an extra field and a plain type CollectionWithCount struct {
Collection
ItemCount int `gorm:"column:item_count"`
}
var top []CollectionWithCount
db.Model(&Collection{}).
Select("collections.*, COUNT(items.id) AS item_count").
Joins("LEFT JOIN items ON items.collection_id = collections.id").
Group("collections.id").
Order("item_count DESC").
Limit(10).
Scan(&top)the join version is usually faster if for either one, make sure you have an index on ref: gorm docs on advanced query / subqueries and joins. |
Uh oh!
There was an error while loading. Please reload this page.
Hello there,
It may be an already asked question but I couldn't find any answer.
Basically, how would you retrieve the N collections with the most items ?
Thanks :)
All reactions