好,所以我认为我的结构还可以,但是在这里,
个人资料地址
type ProfileAddress struct {
gorm.Model
Archive bool `json:"archive"`
Address Address
AddressFK int `gorm:"ForeignKey:id" json:"-"`
Profile Profile
ProfileFK uint `gorm:"ForeignKey:id" json:"-"`
}
地址
type Address struct {
gorm.Model
AddressLine1 string `gorm:"size:255" json:"line1"`
AddressLine2 string `gorm:"size:255" json:"line2"`
AddressLine3 string `gorm:"size:255" json:"line3"`
City string `gorm:"size:200" json:"city"`
Country string `gorm:"size:255" json:"country"`
Postcode string `gorm:"size:12" json:"postcode"`
ProfileAddresses []ProfileAddress `gorm:"foreignkey:address_fk"`
}
个人资料
type Profile struct {
gorm.Model
Company string `gorm:"size:255" json:"company"`
AddedDate time.Time `gorm:"type:date" json:"date_added"`
}
这在构建数据库(在Docker中运行的postgres)时有效。但是当我这样做时,
profileAdd := []structs.ProfileAddress{}
db.Debug().Find( &profileAdd )
我从Profile Address
表中获取数据,但是Address
和Profile
表完全为空。
我也尝试使用Related
和Preload
,但是没有任何作用。
但是,当我使用Raw Query
时,它可以正常工作,就像这样:
rows, err := db.Raw("select addresses.address_line1, addresses.address_line2 from profile_addresses left join addresses on addresses.id = profile_addresses.address_fk where profile_addresses.deleted_at IS NULL").Rows()
if err != nil {
fmt.Println(err)
}
defer rows.Close()
for rows.Next() {
var testData structs.ProfileAddress
rows.Scan(&testData.Address.AddressLine1, &testData.Address.AddressLine2)
profileAdd = append(profileAdd, testData)
}