Has One
,Has Many
和Belong To
的区别是什么
我有3个模型
User
Profile
其中profile
和user
应该有one to one
关系Category
其中category
应该是foreign key
到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
}
ForUser
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
}
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
}
ForUser
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
}
编辑:UserId字段将成为你的外键
如果你想让gorm自动为你创建表,你可以在main.go
中使用AutoMigrate
err := db.AutoMigrate(your_model_package.User{})
if err != nil {
return err
}