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

How to create one to one relationship and foreign key in gorm?

Has OneHas ManyBelong To有什么区别

我有 3 个模型

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

}

对于UserHas 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
}

对于UserHas 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自动为你创建table,你可以在main.go

中使用AutoMigrate
err := db.AutoMigrate(your_model_package.User{})
if err != nil {
    return err
}