doutong2132 2019-06-11 17:53
浏览 474

如何使用GORM初始化具有外键约束的结构并将其插入数据库

I am trying to create a rest API with golang. Each time a user is created, I would like to create a 'Profile' which is associated with that user.

My initial thought was to first create the user, and then separately create the profile referencing the user ID and inserting that into the database.

I'm not sure if this kind of thinking aligns with the way go should be used as i'm just starting with the language.

Using below code, I create the user, but cannot create the profile. I receive this error: using unaddressable value

var db *gorm.DB

func GetDB() *gorm.DB {
    return db
}

type User struct {
    gorm.Model
    Email    string `gorm:"type:varchar(100);unique_index"`
    Password string `json:"password"`
    Name     string `json:"name"`
    Token    string `json:"token";sql:"-"`
}

type Profile struct {
    gorm.Model
    User        User `gorm:"foreignkey:UserRefer"` // use UserRefer as foreign key
    UserRefer   uint
    FirstName   string `gorm:"default:'John'"`
    LastName    string `gorm:"default:'Doe'"`
    Description string `gorm:"default:'Mysterious'"`
}

func (user *User) Create() (map[string]interface{}) {

    if resp, ok := user.Validate(); !ok {
        return resp
    }

    hashedPassword, _ := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
    user.Password = string(hashedPassword)

    GetDB().Create(user)

    profile := Profile{}
    profile.UserRefer = user.ID

    GetDB().Create(profile)

    if user.ID <= 0 {
        return u.Message(false, "Failed to create account, connection error.")
    }

    response := u.Message(true, "Account has been created")
    response["user"] = user

    return response

}

I'm hoping someone will be able to help me understand what is going wrong here?

  • 写回答

1条回答 默认 最新

  • douqingnao9246 2019-06-12 01:44
    关注

    You should pass a pointer on gorm's Create method to get your model Filled after creation...

    GetDB().Create(&profile)
    

    But, as is showed in https://gorm.io/docs/associations.html gorm Auto create the associations.

    You can change your models, like so... (I am supposing that User and Profile has a 1..1 relation ok?) And everything will get done automatically

    type User struct {
        gorm.Model
        Email     string `gorm:"type:varchar(100);unique_index"`
        Password  string `json:"password"`
        Name      string `json:"name"`
        Token     string `json:"token";sql:"-"`
        Profile   Profile
        ProfileID uint
    }
    
    type Profile struct {
        gorm.Model
        UserID      uint
        FirstName   string `gorm:"default:'John'"`
        LastName    string `gorm:"default:'Doe'"`
        Description string `gorm:"default:'Mysterious'"`
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大