beardeadclown
beardeadclown

Reputation: 377

Is it possible to omit FieldID in struct when using gorm?

Looking at an example from their documentation:

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

type Company struct {
  ID   int
  Name string
}

CompanyID field seems rather redundant. Is it possible to get rid of it using some tags on Company field instead?

Upvotes: 2

Views: 137

Answers (2)

Wolfgang
Wolfgang

Reputation: 1398

You can create your own BaseModel instead of using gorm.Model, for example

type BaseModel struct {
    ID        uint       `gorm:"not null;AUTO_INCREMENT;primary_key;"`
    CreatedAt *time.Time
    UpdatedAt *time.Time
    DeletedAt *time.Time `sql:"index"`
}

Then, in the User, do something like this, basically overriding the default Foreign Key

type User struct {
    BaseModel
    Name    string
    Company company `gorm:"foreignKey:id"`
}

And the Company

type Company struct {
  BaseModel
  Name string
}

Upvotes: 0

beardeadclown
beardeadclown

Reputation: 377

Changing User definition like this did the trick:

type User struct {
  gorm.Model
  Name    string
  Company Company `gorm:"column:company_id"`
}

Upvotes: 1

Related Questions