2

I have two models User and Address in GORM defined: File user.go

type User struct {
    gorm.Model
    Identity     string    `json:"identity"`
    Password     string    `json:"password"`
    Address      Address
    AddressID    int
}

type Address struct {
    gorm.Model
    Street       string `json:"street"`
    StreetNumber string `json:"streetnumber"`
}

In the main.go file I initiate the DB, automigrate and want to add a test user to the DB:

database.InitDatabase()

database.DBConn.AutoMigrate(&user.User{})
database.DBConn.AutoMigrate(&user.Address{})

userRec := &user.User{ Identity: "John Wayne", Password: "mysecretpassword", Address: user.Address{Street: "Teststreet", StreetNumber: "1"}}

database.DBConn.Create(userRec)

The user gets created and the address as well, however, the address is not associated with the user, just empty Address fields come up. What did I forget?

Is this the normal way to setup a test entry if you have associations in your entities (with nested models)?

2
  • the address is not associated with the user, just empty Address fields come up AddressID is not set in database ?
    – Eklavya
    Commented Sep 28, 2020 at 15:10
  • @Eklavya Yes, the AddressID in the user entry is set to default value (here 0). Why does it not assiociate with the genereated Address entry? Commented Sep 28, 2020 at 15:13

1 Answer 1

1

Try using the "address_id" field as a foreignKey.

for example

type User struct {
    gorm.Model
    Identity     string     `json:"identity"`
    Password     string     `json:"password"`
    Address      Address    `gorm:"foreignKey:address_id;association_autoupdate:false"`
    AddressID    uint       `json:"address_id"`
}

Online documentation

Maybe it will help.

4
  • Thank you @DonPepemon. This seems to get the right foreignKey into the AddressID field. However, when I want to query all users I don't get the associations delivered (just again default values for Address): var users []user.User and database.DBConn.Find(&users). Commented Sep 29, 2020 at 14:07
  • 1
    nevermind. I tested to values in Insomnia as HTTP GET response and you explicitly included ` json:"-"` which deleted the nested object in the response of c.json(users). Is there a reason why you added ` json:"-"` ? Commented Sep 29, 2020 at 14:29
  • 1
    This can be done easily with golang code, not just SQL queries. This is my mistake, json: "-" isn't needed here.
    – DonPepemon
    Commented Sep 29, 2020 at 14:33
  • 2
    @Heikkisorsa "when I want to query all users I don't get the associations delivered" - You need to Preload (eager load) the association, by calling database.DBConn.Preload("Address").Find(&users) Commented Oct 1, 2020 at 18:32

Not the answer you're looking for? Browse other questions tagged or ask your own question.