Search code examples
goassociationsgo-gorm

Associations not working with test entries


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)?


Solution

  • 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.