Golang: GORM Association

Has Many

Company has many Employees.

type Company struct {
        gorm.Model
        Name      string
        Employees []Employee
}

type Employee struct {
        gorm.Model
        Name      string
        CompanyID uint
}

Has Many – Belongs To

You just need to add Company Company inside Employee struct.

type Company struct {
        gorm.Model
        Name      string
        Employees []Employee
}

type Employee struct {
        gorm.Model
        Name      string
        CompanyID uint
        Company   Company
}

Has One

Account has one Profile.

type Account struct {
        gorm.Model
        Username string
        Profile  Profile
}

type Profile struct {
        gorm.Model
        Name      string
        AccountID uint
}

Has One – Belongs To

Unlike Has Many relationship, you can not just add Account Account inside the Profile struct. If you do, you will get an error something like this invalid recursive type Account. You need to add pointer to Account (*Account) to get this working.

type Account struct {
        gorm.Model
        Username string
        Profile  Profile
}

type Profile struct {
        gorm.Model
        Name      string
        AccountID uint
        Account   *Account
}

Many To Many

...

Personal note:

  • Use pointer for struct variable

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *