One to many with subquery join does not get scanned to the parent struct
type Chat struct {
ID string `json:"id" gorm:"primaryKey"`
Message string `json:"message"`
SenderId string `json:"senderId"`
ReceiverId string `json:"receiverId"`
ConversationId string `json:"conversationId"`
Conversation *Conversation `json:"conversation" gorm:"foreignKey:ConversationId;references:ID"`
OrgId string `json:"orgId"`
CreatedAt int `json:"createdAt" gorm:"autoCreateTime;"`
}
type Conversation struct {
ID string `json:"id" gorm:"primaryKey"`
User1Id string `json:"user1Id"`
User2Id string `json:"user2Id"`
OrgId string `json:"orgId"`
Chats []*Chat `json:"chats"`
CreatedAt int `json:"createdAt" gorm:"autoCreateTime"`
}
Above are two gorm models Conversation and Chat. Im trying to query the Conversation table and each get the latest chat for each conversation. Something like a preload but with limit. There is this issue that i tried to follow but trying another alternative way which is using subquery with a limit.
The ToSQL() outputs this:
SELECT `conversations`.`id`,`conversations`.`user1_id`,`conversations`.`user2_id`,`conversations`.`org_id`,`conversations`.`created_at` FROM `conversations` LEFT JOIN (SELECT chats.* FROM `chats` ORDER BY chats.created_at DESC LIMIT 1) chats ON chats.conversation_id = conversations.id LIMIT 21
Which looks correct, however the data that is scanned to the Conversation struct does not include Chats.
Docs does not show a way to scan results into structs of one to many relations
https://gorm.io/docs/advanced_query.html#SubQuery
Is there a way to populate the chats relation within conversation without using preloads?
Comment From: github-actions[bot]
The issue has been automatically marked as stale as it missing playground pull request link, which is important to help others understand your issue effectively and make sure the issue hasn't been fixed on latest master, checkout https://github.com/go-gorm/playground for details. it will be closed in 30 days if no further activity occurs. if you are asking question, please use the Question template, most likely your question already answered https://github.com/go-gorm/gorm/issues or described in the document https://gorm.io ✨ Search Before Asking ✨