如何在 gorm 中创建一对一关系和外键?
How to create one to one relationship and foreign key in gorm?
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
}
对于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
}
对于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
}
对于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
}
编辑:UserId 字段将成为您的外键。
如果你想让gorm自动为你创建table,你可以在main.go
中使用AutoMigrate
err := db.AutoMigrate(your_model_package.User{})
if err != nil {
return err
}
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
}
对于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
}
对于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
}
对于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
}
编辑:UserId 字段将成为您的外键。
如果你想让gorm自动为你创建table,你可以在main.go
中使用AutoMigrate
err := db.AutoMigrate(your_model_package.User{})
if err != nil {
return err
}