Home > database >  How to create one to one relationship and foreign key in gorm?
How to create one to one relationship and foreign key in gorm?

Time:05-31

What is the difference between Has One, Has Many and Belong To

I have 3 Models

  • User
  • Profile Where profile and user should have one to one relationship
  • Category Where category should be foreign key to user
type User struct {
gorm.Model
Email *string
Name string
...
}

type Profile struct {
gorm.Model
Phone string
Address string
...

}

type Category struct {
gorm.Model
Name string

}

CodePudding user response:

For User Has One Profile

type User struct {
   gorm.Model
   Email *string
   Name string
   Profile Profile //this is the key different
}
type Profile struct {
   gorm.Model
   UserId int //this is important
   Phone string
   Address string
}

For Profile Belong To User

type User struct {
   gorm.Model
   Email *string
   Name string
}
type Profile struct {
   gorm.Model
   UserId int //this is important
   User User //this is the key different
   Phone string
   Address string
}

For User Has Many Category

type User struct {
   gorm.Model
   Email *string
   Name string
   CategoryList []Category
}
type Category struct {
   gorm.Model
   UserId int //this is important
   Name string
}

Edit: UserId field will become your foreign key.

If you want gorm to automatically create table for you, you can use AutoMigrate in main.go

err := db.AutoMigrate(your_model_package.User{})
if err != nil {
    return err
}
  • Related