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 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法