-
-
Notifications
You must be signed in to change notification settings - Fork 350
Open
Description
Your Question
When a model has two foreign key relations pointing to the same type, GORM Gen only generates nested preload paths for the first relation.
Minimal Example
type Address struct {
ID uint64 `gorm:"primaryKey"`
Street string
City string
Country string
}
type User struct {
ID uint64 `gorm:"primaryKey"`
Name string
AddressID uint64
Address Address `gorm:"foreignKey:AddressID"`
}
type Order struct {
ID uint64 `gorm:"primaryKey"`
User1ID uint64
User1 User `gorm:"foreignKey:User1ID"`
User2ID uint64
User2 User `gorm:"foreignKey:User2ID"`
}Generator:
g := gen.NewGenerator(gen.Config{
OutPath: "./query",
Mode: gen.WithoutContext | gen.WithDefaultQuery,
})
g.ApplyBasic(Address{}, User{}, Order{})
g.Execute()Expected Generated Code:
Both User1 and User2 should have nested Address:
type orderDo struct {
User1 struct {
field.RelationField
Address struct {
field.RelationField
}
}
User2 struct {
field.RelationField
Address struct { // ← Should exist
field.RelationField
}
}
}Actual Generated Code
Only User1.Address exists:
type orderDo struct {
User1 struct {
field.RelationField
Address struct {
field.RelationField
}
}
User2 struct {
field.RelationField
// ← Address is missing!
}
}Impact
order := query.Order
// Works:
order.Preload(order.User1.Address).Find() // ✅
// Compile error:
order.Preload(order.User2.Address).Find() // ❌ User2.Address doesn't exist
// No type-safe workaround available!Versions:
- go: 1.21.1
- gorm.io/gen v0.3.27
- gorm.io/gorm v1.31.1
Expected answer
Am I doing something wrong?
- Is my model definition incorrect?
- Is there a special configuration needed in the generator?
- Should I define the relations differently?
Is there any workaround?
- Can I generate the missing nested paths somehow?
- Is there a way to force Gen to create all nested preload paths?
Is this a bug?
- Should GORM Gen generate nested preload paths for all relations of the same type, not just the first one?
- This pattern (multiple relations to the same type) is common in real-world scenarios: orders with buyer/seller, messages with sender/receiver, transactions with payer/payee, etc.
Metadata
Metadata
Assignees
Labels
No labels