登录
首页 >  Golang >  Go问答

gorm中如何建立一对一关联以及外键的创建方法?

来源:stackoverflow

时间:2024-02-07 15:48:25 299浏览 收藏

“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《gorm中如何建立一对一关联以及外键的创建方法?》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!

问题内容

has onehas manybelong to 有什么区别

我有 3 个模型

  • 用户
  • profile 其中 profileuser 应该具有 one 到 one 关系
  • category 其中 category 应该是 外键 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

}

正确答案


对于用户 有一个 配置文件

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
}

对于个人资料 属于 用户

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
}

对于用户 有很多 类别

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
}

以上就是《gorm中如何建立一对一关联以及外键的创建方法?》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>