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

时间:2019-08-19 05:57:15

标签: go go-gorm

我正在尝试使用gorm向模型添加外键。我应该如何将User模型的对象作为外键传递给Profile模型?

我的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 个答案:

答案 0 :(得分:0)

问题的代码将在user(id=1)profile(id = 1)之间建立关联

您还可以使用Association附加外键值。

var user User
db.First(&user, 1) 
db.Model(&user).Association("Refer").Append(user)