Has One vs Belongs To in GORM

Viewed 39

What is the difference between Has One and Belongs To in GORM? Where is each used?

Thanks.

I read the documentation, but I did not understand the difference and their uses.

1 Answers

Both of them are used to create one-to-one connection with another model, the differences between them I think it's self-explanatory as its documentation said.

Belongs To

type User struct {
  gorm.Model
  Name      string
  CompanyID int
  Company   Company
}

type Company struct {
  ID   int
  Name string
}

Like the example above, the user can only work in one company, there is no chance user can do other work in multiple companies since the user only belongs to one company.

Has One

type User struct {
  gorm.Model
  CreditCard CreditCard
}

type CreditCard struct {
  gorm.Model
  Number string
  UserID uint
}

Otherwise, the has one relationship guarantee that each model can only have one another model. In the example above the user can only have one credit card and the credit card can only belong to exactly one user as its owner.

And when to use one over another depends on the entity and the main business of your application. Thanks, hope that help.

Related