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, the following types represent that relationship. Notice here that, on the User
object, there is both a CompanyID
as well as a Company
. By default, the CompanyID
is implicitly used to create a foreign key relationship between the User
and Company
tables, and thus must be included in the User
struct in order to fill the Company
inner struct.
// `User` belongs to `Company`, `CompanyID` is the foreign key |
Refer to Eager Loading for details on populating the inner struct.
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 { |
NOTE GORM usually guess the relationship as
has one
if override foreign key name already exists in owner’s type, we need to specifyreferences
in thebelongs to
relationship.
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 { |