当前位置:网站首页>[Gorm] model relationship -hasone
[Gorm] model relationship -hasone
2022-07-26 23:54:00 【Viva Python】
One 、 summary
HasOneEstablish a one-to-one relationship with another model , This association indicates that each instance of a model contains or owns another model instance .
Two 、 model
Realization
HasOneModel , The owner needs to define the model variables of the owner ( Associate model variables ), And specify :(1) Foreign keys : stay Owner Defined in the model , Mark in the associated model variable . The default is
Owner model name ID, It needs to be explicitly defined in the association model .(2) quote : stay The owner Defined in the model , The type should be the same as that of the foreign key variable The same type , Mark in the associated model variable , The default is the primary key of the associated model .
To the user
UserHaveCreditCardFor example , The model is defined as follows :(1)
CreditCardAssociate model variables , Foreign key defaults toCreditCardModelUserID, Referenced asUserModelID.// Owner model . type User struct { ID uint `gorm:"primary_key"` // Default reference Password string `gorm:"->:false;<-"` CreditCard CreditCard // Associate model variables . } // Association model . type CreditCard struct { ID uint `gorm:"primary_key"` UserID uint // Default foreign key , You need to explicitly define . Number string `gorm:"type:varchar(20)"` }(2) After building the table , stay
CredictCardIn the table , A new field will be addeduser_id, It means that we shouldCreditCardRecord the information associated with itUserPrimary key .UserTable field description

CreditCardTable field description

3、 ... and 、 redefinition
1. Redefine foreign keys
- Redefine foreign keys , That is, the fields that point to references in the association model , It needs to be marked in the associated model variables .
- Redefine as follows
UserReferFor foreign key , UseforeignKeyAnnotate associated model variablesCreditCard.
type User struct {
ID uint `gorm:"primary_key"`
Name string
Password string `gorm:"->:false;<-"`
CreditCard CreditCard `gorm:"foreignKey:UserRefer"`
}
type CreditCard struct {
ID uint `gorm:"primary_key"`
UserRefer uint
Number string `gorm:"type:varchar(20)"`
}
2. Redefine reference
- Redefine reference , That is, the identifier pointed by the foreign key , It needs to be marked in the associated model variables .
- Redefine as follows
NameCiting .
type User struct {
ID uint `gorm:"primary_key"`
Name string
Password string `gorm:"->:false;<-"`
CreditCard CreditCard `gorm:"foreignKey:UserName;references:Name"`
}
type CreditCard struct {
ID uint `gorm:"primary_key"`
UserName string
Number string `gorm:"type:varchar(20)"`
}
Four 、 The relevant operation
- The following operations are based on
HasOneAssociation model
type User struct {
ID uint `gorm:"primary_key"`
Name string
Password string `gorm:"->:false;<-"`
CreditCard CreditCard `gorm:"foreignKey:UserName;references:Name"`
}
type CreditCard struct {
ID uint `gorm:"primary_key"`
UserName string
Number string `gorm:"type:varchar(20)"`
}
1. preservation
- Declare the complete structure variable , call
SaveMethod to save .
func TestSaveUser() {
user := User{
Name: "Jason",
Password: "12345",
CreditCard: CreditCard{
Number: "1234567890",
},
}
err := SaveUser(user)
if err != nil {
log.Println(" User save failed !")
} else {
log.Println(" User saved successfully !")
}
}
func SaveUser(user User) error {
err := db.Save(&user).Error
return err
}
2. Delete
- There are two strategies for deleting instances :
(1) together with HasOne The associated object record is deleted , After deleting the user as above, delete it together with the account record . use Select Method . as follows , Use Select Method to select the associated model , Delete together with the model record .
func DeleteUserByName(name string) error {
var user User
var err error
db.Model(&user).Where("name = ?", name).First(&user)
err = db.Model(&user).Select("CreditCard").Delete(&user).Error
return err
}
(2) Do not delete the associated model record , And (1) type , Don't use Select Method .
3. Inquire about
When querying, you need Load the associated model , Use
PreloadMethod loading .func GetUserByName(name string) (User, error) { var user User err := db.Model(&user).Preload("CreditCard").Where("name = ?", name).First(&user).Error return user, err }
边栏推荐
- 文件上传到服务器
- Re understand the life world and ourselves
- Which securities company has the lowest commission? Is online account opening safe
- Paging plug-in -- PageHelper
- [H5 bottom scrolling paging loading]
- Part II - C language improvement_ 6. Multidimensional array
- In simple terms, cchart daily lesson - happy high school lesson 57 new starting point, the old tree and new bud of colorful interface library
- C language array
- Azure Synapse Analytics 性能优化指南(4)——使用结果集缓存优化性能
- Tensorflow2.0 深度学习运行代码简单教程
猜你喜欢

Bid farewell to wide tables and achieve a new generation of Bi with DQL

MVC three-tier architecture
![[2016] [paper notes] differential frequency tunable THz technology——](/img/7e/71126950250997fc436a4ee730aee7.png)
[2016] [paper notes] differential frequency tunable THz technology——

Dynamic SQL

Baidu website Collection

04 traditional synchronized lock

Chapter 1 requirements analysis and SSM environment preparation

动态sql

第二部分—C语言提高篇_9. 链表

第二部分—C语言提高篇_12. 动/精态库的封装和使用
随机推荐
Silicon Valley class lesson 5 - Tencent cloud object storage and course classification management
告别宽表,用 DQL 成就新一代 BI
Upload files to the server
【不积跬步无以至千里】统计日志指定时间段内的关键词
Tensorflow2.0 deep learning simple tutorial of running code
第1章 拦截器入门及使用技巧
会议OA项目排座功能以及送审功能
银河证券网上开户佣金,网上客户经理开户安全吗
第6节:cmake语法介绍
Part II - C language improvement_ 5. Bit operation
In depth interpretation of the investment logic of the consortium's participation in the privatization of Twitter
买不到的数目
Azure Synapse Analytics 性能优化指南(4)——使用结果集缓存优化性能
Application of workflow engine in vivo marketing automation | engine 03
【C语言】数组
[literature reading] hat: hardware aware transformers for efficient natural language processing
Positioning of soaring problems caused by online MySQL CPU
15_ Key function and principle
Dynamic SQL
股票开户佣金是否可以调整?手机上开户安不安全