douyi1341 2019-08-19 05:57
浏览 1053
已采纳

如何使用Gorm向模型添加外键

I am trying to add foreign key to a model using gorm. How should I pass an object of User Model as foreign key to Profile Model?

My main.go:

package main

import (
    "fmt"

    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/sqlite"
)

type User struct {
    gorm.Model
    Refer string
    Name  string
}

type Profile struct {
    gorm.Model
    Name      string
    User      User `gorm:"association_foreignkey:Refer"` // use Refer as association foreign key
    UserRefer string
}

func main() {
    db, err := gorm.Open("sqlite3", "test.db")
    if err != nil {
        panic("failed to connect database")
    }
    defer db.Close()

    // Migrate the schema
    db.AutoMigrate(&User{})
    db.AutoMigrate(&Profile{})

    // Create
    db.Create(&User{Name: "Clifton"})

    // Read
    var user User
    db.Debug().First(&user, 1)
    db.Debug().Create(&Profile{Name: "Clifton",
        UserRefer: "yyyyy"}).Association("User").Append(user)
    // db.Debug().Model(&user).Association("Refer").Append(user)
    var profile Profile
    db.Debug().Find(&profile, 1)
    fmt.Println(profile.Name, profile.UserRefer, profile.User.ID, profile.User.CreatedAt)

}
  • 写回答

1条回答 默认 最新

  • douziqian2871 2019-08-19 09:35
    关注

    The code of the question will create the association between the user(id=1) and the profile(id = 1)

    You can also use Association to append foreign keys values.

    var user User
    db.First(&user, 1) 
    db.Model(&user).Association("Refer").Append(user)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?