How to handle relationship preloading with CLI-generated raw SQL queries?
- Dominant language
- Go
- Stars
- 108
- Forks
- 15
- PR merge metrics
- No merged PRs in 30d
Description
## 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:
```go
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:
```go
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:
```go
// 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.
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.