ok, so I think my structs are ok, but here they are,
Profile Address
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:"-"`
}
Address
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"`
}
Profile
type Profile struct {
gorm.Model
Company string `gorm:"size:255" json:"company"`
AddedDate time.Time `gorm:"type:date" json:"date_added"`
}
This is works when building my database (postgres running in Docker). But when I do this,
profileAdd := []structs.ProfileAddress{}
db.Debug().Find( &profileAdd )
I get the data from the Profile Address
table but the Address
& Profile
tables are completely empty.
I have also tried using Related
and Preload
but nothing is working.
However, I can get it to work when I use a Raw Query
, like so:
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)
}