go-gorm / gorm.io

GORM official site
https://gorm.io
248 stars 348 forks source link

[Question] Bad examples about nested struct #772

Open lijinliangyihao opened 1 month ago

lijinliangyihao commented 1 month ago

Document Link

https://gorm.io/docs/preload.html#Embedded-Preloading

Your Question

The examples about nested struct are very confusing and have some errors.

the doc's here:


type Address struct {  
  CountryID 
  int  Country   
  Country
}
type Org struct {  
  PostalAddress   Address `gorm:"embedded;embeddedPrefix:postal_address_"`  
  VisitingAddress Address `gorm:"embedded;embeddedPrefix:visiting_address_"`  
  Address         struct {    
    ID int    
    Address  
  }
}
// Only preload Org.Address and Org.Address.Country
db.Preload("Address.Country")  // "Address" is has_one, "Country" is belongs_to (nested association)

>>> Comment is wrong, should be PostalAddress
// Only preload Org.VisitingAddress
db.Preload("PostalAddress.Country") // "PostalAddress.Country" is belongs_to (embedded association)

>>> Comment is wrong, where's the NestedAddress?
// Only preload Org.NestedAddress
db.Preload("NestedAddress.Address.Country") // "NestedAddress.Address.Country" is belongs_to (embedded association)
// All preloaded include "Address" but exclude "Address.Country", because it won't preload nested associations.db.Preload(clause.Associations)

If no "embedded" tag on field "Org.Address",the generated sql‘s table name will be empty string, please give a more detailed example.

Expected answer

a631807682 commented 1 month ago

Can you create a PR for it?