How to handle relationship preloading with CLI-generated raw SQL queries?
I'm using GORM CLI to generate type-safe query methods from raw SQL templates. This works great for complex queries, but I'm unsure of the recommended pattern for handling relationship preloading when using CLI-generated queries.
For example, I have 2 models with a relationship:
type Post struct {
gorm.Model
Title string
Content string
UserID int
Comments []Comment `gorm:"foreignKey:PostID"`
}
type Comment struct {
gorm.Model
PostID int
Text string
UserID int
}
And a CLI-generated query for complex post retrieval:
type PostQuery[T any] interface {
// SELECT p.* FROM @@table p
// JOIN user_engagement ue ON ue.post_id = p.id
// WHERE ue.score > @minScore
// GROUP BY p.id
// HAVING COUNT(DISTINCT ue.user_id) > @minUsers
GetHighEngagementPosts(minScore float64, minUsers int) ([]T, error)
}
In this case, what's the recommended pattern for loading the Comments relationship when using CLI-generated queries? Currently, I am doing a two step loading:
// Step 1: Use CLI-generated query
posts, err := generated.PostQuery[Post](db).GetHighEngagementPosts(ctx, 8.0, 10)
// Step 2: Reload with GORM generic API to get preloads
postIDs := extractIDs(posts)
postsWithComments, err := gorm.G[Post](db).
Where(generated.Post.ID.In(postIDs)).
Preload("Comments", nil).
Find(ctx)
This is fine, but is a bit too cumbersome and requires two queries. Alternatively, I could manually join in sql and then try manually reconstructing in Scan, but that is also ugly.
Is there (or could there be) a way to:
- Use CLI-generated queries for complex SELECT logic
- Still leverage GORM's Preload mechanism without reloading the primary records
- Maintain type safety throughout?
Thank you for your work on CLI.
How to handle relationship preloading with CLI-generated raw SQL queries?
I'm using GORM CLI to generate type-safe query methods from raw SQL templates. This works great for complex queries, but I'm unsure of the recommended pattern for handling relationship preloading when using CLI-generated queries.
For example, I have 2 models with a relationship:
And a CLI-generated query for complex post retrieval:
In this case, what's the recommended pattern for loading the
Commentsrelationship when using CLI-generated queries? Currently, I am doing a two step loading:This is fine, but is a bit too cumbersome and requires two queries. Alternatively, I could manually join in sql and then try manually reconstructing in
Scan, but that is also ugly.Is there (or could there be) a way to:
Thank you for your work on CLI.