如何在 gorm 中创建一对一关系和外键?

Has OneHas Many有什么区别 Belong To

我有 3 个模型

  • User

  • Profile哪里profileuser应该有one to one关系

  • Categorycategory应该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


}


犯罪嫌疑人X
浏览 165回答 1
1回答

DIEA

为了User Has One Profiletype 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 Usertype 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 Categorytype User struct {   gorm.Model   Email *string   Name string   CategoryList []Category}type Category struct {   gorm.Model   UserId int //this is important   Name string}编辑:UserId 字段将成为您的外键。如果你想让 gorm 自动为你创建表,你可以AutoMigrate在 main.go中使用err := db.AutoMigrate(your_model_package.User{})if err != nil {    return err}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go