Reputation: 5056
In the documentation we have this example:
type User struct {
gorm.Model
Name string
}
// `Profile` belongs to `User`, `UserID` is the foreign key
type Profile struct {
gorm.Model
UserID int
User User
Name string
}
If I do something like profile.User = &user
, will that automatically populate the UserID
field? Is it recommended to set both? Like:
profile.User = &user
profile.UserID = &user.ID
Or is that pointless? Furthermore, could I alternatively just set the UserID
field and ignore the User
field entirely?
Upvotes: 1
Views: 330
Reputation: 4662
If I do something like
profile.User = &user
, will that automatically populate the UserID field?
Just writing profile.User = &user
will not populate the UserID
field. Once you add the profile
to the database. gorm will automatically populate the foreign key.
Is it recommended to set both?
Nope. In fact, you should not set the UserID
yourself. This answers the last question as well.
Upvotes: 2