Home > Software design >  Should I explicitly create a relation symmetrical to "Belongs To" or "Has Many"?
Should I explicitly create a relation symmetrical to "Belongs To" or "Has Many"?

Time:03-18

I am new to ORM (and GORM) so apologies if this is an obvious question, but it does not seem to be covered by the documentation.

I will be using the examples from the documentation as a base to my questions

Question 1: Belongs To

// `User` belongs to `Company`, `CompanyID` is the foreign key
type User struct {
  gorm.Model
  Name      string
  CompanyID int
  Company   Company
}

type Company struct {
  ID   int
  Name string
}
  • A User belongs to one Company only → this is handled by the code above
  • A Company has many Useris this implied by the code above? Or should I add somehow a relation O2M in Company?

Question 2: Has Many

// User has many CreditCards, UserID is the foreign key
type User struct {
  gorm.Model
  CreditCards []CreditCard
}

type CreditCard struct {
  gorm.Model
  Number string
  UserID uint
}
  • A User has 1 CreditCard→ this is handled by the code
  • A CreditCard can belong to several users (say, a shared family CC) → is it implied? (if not: how to set up the O2M relationship).
    Or is it, instead, a case where a CreditCard is explicitly configured to belong to only one user?

CodePudding user response:

Q1: Based on how you defined your structs, you don't need an explicit O2M relationship in the Company struct, but when loading Company details, if you want to load all users that are assigned to that specific company, you need to add that field as well. It will need an additional function call like Preload or Joins, but you shouldn't need an explicit definition of this relationship.

type Company struct {
  ID   int
  Name string
  Users []User
}

Q2: The way the relationship is defined now, it is configured so that a CreditCard belongs to only one user. If you want a many2many relationship, you need to specify the relation table. There is more documentation on it here, but it should look something like this:

type User struct {
  gorm.Model
  CreditCards []CreditCard `gorm:"many2many:users_creditcards"`
}

type CreditCard struct {
  gorm.Model
  Number string
}
  • Related