【问题标题】:How to make foreign key using gorm如何使用gorm制作外键
【发布时间】:2018-10-26 18:10:07
【问题描述】:

我有这两个模型:

用户模型:

type User struct {
    DBBase
    Email    string `gorm:"column:email" json:"email"`
    Password string `gorm:"column:password" json:"-"`
}

func (User) TableName() string {
    return "t_user"
}

用户信息模型:

type UserInfo struct {
    User      User   `gorm:"foreignkey:u_id;association_foreignkey:id"`
    UID       uint   `gorm:"column:u_id" json:"-"`
    FirstName string `gorm:"column:first_name" json:"first_name"`
    LastName  string `gorm:"column:last_name" json:"last_name"`
    Phone     string `gorm:"column:phone" json:"phone"`
    Address   string `gorm:"column:address" json:"address"`
}

func (UserInfo) TableName() string {
    return "t_user_info"
}

我想让 UID 与用户表的 id 相关。

这是创建用户的函数:

func (dao *AuthDAO) Register(rs app.RequestScope, user *models.User, userInfo *models.UserInfo) (userErr error, userInfoErr error) {
    createUser := rs.Db().Create(&user)
    userInfo.UID = user.ID
    createUserInfo := rs.Db().Create(&userInfo)

    return createUser.Error, createUserInfo.Error
}

我确实尝试了 gorm 在文档中写的内容,但没有成功: http://doc.gorm.io/associations.html

【问题讨论】:

  • 你尝试了什么?
  • @Devon “属于”部分
  • 是的......那部分是什么?您没有在上述代码中包含任何关系。
  • @Devon,对不起,你说得对。我编辑了代码。谢谢。
  • 外键应该是UID,如果是id则不需要关联外键。

标签: go go-gorm


【解决方案1】:

解决办法是在迁移数据库的时候加上这行:

db.Model(&models.UserInfo{}).AddForeignKey("u_id", "t_user(id)", "RESTRICT", "RESTRICT")

migration (gorm documentation)

【讨论】:

  • 感谢您的回复!
【解决方案2】:

阅读https://gorm.io/docs/belongs_to.html中的属于关系 另外,这里有一个很好的例子:https://medium.com/@the.hasham.ali/how-to-use-uuid-key-type-with-gorm-cc00d4ec7100

// User is the model for the user table.
type User struct {
 Base
 SomeFlag bool    `gorm:"column:some_flag;not null;default:true"`
 Profile  Profile
}// Profile is the model for the profile table.
type Profile struct {
 Base
 Name   string    `gorm:"column:name;size:128;not null;"`
 UserID uuid.UUID `gorm:"type:uuid;column:user_foreign_key;not null;"`
}

【讨论】:

    【解决方案3】:

    我们可以在最新版本中使用CreateConstraint添加外键约束。

    示例: 假设我们有两个实体

    type User struct {
      gorm.Model
      CreditCards []CreditCard
    }
    
    type CreditCard struct {
      gorm.Model
      Number string
      UserID uint
    }
    

    现在为用户和信用卡创建数据库外键

    db.Migrator().CreateConstraint(&User{}, "CreditCards")
    db.Migrator().CreateConstraint(&User{}, "fk_users_credit_cards")
    

    转换为 Postgres 的以下 SQL 代码:

    ALTER TABLE `credit_cards` ADD CONSTRAINT `fk_users_credit_cards` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`)
    

    参考:

    【讨论】:

      【解决方案4】:

      对于 Gorm 的最新版本,即1.21.x如果您有一对一的字段映射并且没有父子映射,那么您将执行以下操作

      type BaseConfig struct {
          ID         uuid.UUID       `gorm:"primary_key" json:"id"`
      }
      
      type Ledger struct { 
          BaseConfigId        uuid.UUID       `json:"base_config_id"`
          BaseConfig BaseConfig               `gorm:"column:base_config_id;constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"`
      
      }
      

      在迁移脚本中,您需要按照docs 进行操作

      WriteClient.Migrator().CreateConstraint(&models.BaseConfig{}, "Ledgers")
      WriteClient.Migrator().CreateConstraint(&models.BaseConfig{}, "fk_base_configs_id")
      

      我觉得关键点是缺少有关如何关联的文档。可能会有一些杂耍来解决这个问题,所以希望我的回答能节省一些时间。

      【讨论】:

        猜你喜欢
        • 2020-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-09
        • 1970-01-01
        相关资源
        最近更新 更多