Belongs To
A belongs to
association sets up a one-to-one connection with another model, such that each instance of the declaring model “belongs to” one instance of the other model.
For example, if your application includes users and profiles, and each profile can be assigned to exactly one user
type User struct { |
Foreign Key
To define a belongs to relationship, the foreign key must exists, default foreign key uses owner’s type name plus its primary key.
For the above example, to define a model that belongs to User
, the foreign key should be UserID
.
GORM provides a way to customize the foreign key, for example:
type User struct { |
Association ForeignKey
For a belongs to relationship, GORM usually uses the owner’s primary key as the foreign key’s value, for above example, it is User
‘s ID
.
When you assign a profile to a user, GORM will save user’s ID
into profile’s UserID
field.
You are able to change it with tag association_foreignkey
, e.g:
type User struct { |
Working with Belongs To
You could find belongs to
associations with Related
db.Model(&user).Related(&profile) |
For advanced usage, refer Association Mode