What is the difference between Has One
, Has Many
and Belong To
I have 3 Models
User
Profile
Whereprofile
anduser
should haveone to one
relationshipCategory
Wherecategory
should beforeign key
touser
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
}