I have a following data structure:
type Collection struct {
gorm.Model
Name string
CollectionItems []CollectionItem
}
type CollectionItem struct {
CollectionID uint
ItemID uint
Item
}
How can I query collections
table ordering results by a number of collection_item
associations i.e. collections with most items come first.
Thanks.
There is no such feature like rails counter cache
in the gorm, but gorm has callbacks before*
& after*
so it is easy to implement order by collection count feature.
For example:
// Updating data in same transaction
func (c *Collection) AfterUpdate(tx *gorm.DB) (err error) {
tx.Model(&Collection{}).Where("id = ?", c.ID).Update("items_count", gorm.Expr("items_count + ?", 1))
return
}