大家好,今天本人给大家带来文章《如何使用 GORM 将外键添加到模型中》,文中内容主要涉及到,如果你对golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!问题内容我
大家好,今天本人给大家带来文章《如何使用 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的相关知识,请关注编程网公众号!
--结束END--
本文标题: 如何使用 Gorm 将外键添加到模型中
本文链接: https://www.lsjlt.com/news/596421.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-04-05
2024-04-05
2024-04-05
2024-04-04
2024-04-05
2024-04-05
2024-04-05
2024-04-05
2024-04-04
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0