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 companies, and each user can be assigned to exactly one company
// `User` belongs to `Company`, `CompanyID` is the foreign key |
Override Foreign Key
To define a belongs to relationship, the foreign key must exist, the default foreign key uses the owner’s type name plus its primary field name.
For the above example, to define the User
model that belongs to Company
, the foreign key should be CompanyID
by convention
GORM provides a way to customize the foreign key, for example:
type User struct { |
Override References
For a belongs to relationship, GORM usually uses the owner’s primary field as the foreign key’s value, for the above example, it is Company
‘s field ID
.
When you assign a user to a company, GORM will save the company’s ID
into the user’s CompanyID
field.
You are able to change it with tag references
, e.g:
type User struct { |
CRUD with Belongs To
Please checkout Association Mode for working with belongs to relations
Eager Loading
GORM allows eager loading belongs to associations with Preload
or Joins
, refer Preloading (Eager loading) for details
FOREIGN KEY Constraints
You can setup OnUpdate
, OnDelete
constraints with tag constraint
, it will be created when migrating with GORM, for example:
type User struct { |