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



Has One,Has ManyBelong To的区别是什么

我有3个模型

  • User
  • Profile其中profileuser应该有one to one关系
  • Category其中category应该是foreign keyuser
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
}

ForUserHas OneProfile

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
}

ProfileBelong ToUser

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
}

ForUserHas ManyCategory

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
}

相关内容

  • 没有找到相关文章

最新更新