(Initially asked in SO - I will synchronize answers if any)

Your Question

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?

The document you expected this should be explained

An addition about the symmetrical to each relationship description in the documentation

Comment From: github-actions[bot]

This issue has been automatically marked as stale because it has been open 360 days with no activity. Remove stale label or comment or this will be closed in 180 days