登录
首页 >  Golang >  Go问答

如何使用 Gorm 将外键添加到模型中

来源:stackoverflow

时间:2024-04-01 19:27:28 284浏览 收藏

大家好,今天本人给大家带来文章《如何使用 Gorm 将外键添加到模型中》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

问题内容

我正在尝试使用 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)

}

解决方案


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

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

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

本篇关于《如何使用 Gorm 将外键添加到模型中》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>