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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?