Search code examples
goassociationsone-to-manygo-gorm

One-to-many associations not working with test entries


Similar to this question, but in the case of one-to-many: Associations not working with test entries

I have two models User and E-Mails in GORM defined: File user.go

type User struct {
    gorm.Model
    Identity     string    `json:"identity"`
    Password     string    `json:"password"`
    Emails       []Email

}

type Email struct {
    gorm.Model
    UserID     uint
    Text       string `json:"text"`
    Sender     string `json:"sender"`
}

According to the documentation this should work with a test entry:

userRec := &user.User{ Identity: "John Wayne", Password: "mysecretpassword", Emails: []user.Email{user.Email{Text: "My Text", Sender: "[email protected]"}, user.Email{Text: "My Text", Sender: "[email protected]"}}}

However, the Email entries do not get associated with the User object.

Is it normal that the User object does not have entries to which Email objects it is referring to (as opposed to the "refer to" case)?

How can I query a User with all the corresponding Email objects?

All Emails are available via

var emails[] Email
db.Where("user_id = ?", id).Find(&emails)

Solution

  • You need to Preload (eager load) the emails table, by referring to its column name:

    user := &User{}
    db.Preload("Emails").First(user)
    

    If you are using one-to-one relations, you can also do it automatically by calling:

    db.Preload(clause.Associations).Find(user)
    

    Note: This will not work for one-to-many relations.

    There is some other functionality supported, such as nested Preloading, and combining joins and preloads together (for the purpose of filtering or ordering on sub-tables) defined in the GORM Docs