使用GORM选择相关字段
我是来自python背景的Golang的新手,所以尝试了解新的和不同的概念。我正在尝试创建相关字段,然后从数据库中选择它们。
楷模:
type Company struct { gorm.Model
Name string
}
type CreditCard struct {
gorm.Model
Number int
Company Company
CompanyId uint
}
type User struct {
gorm.Model
Name string
CreditCard CreditCard
CreditCardID uint
}
创建表和行并从数据库中选择
common.DB.AutoMigrate( &Company{},
&CreditCard{},
&User{},
)
user := User{
Name: "Alice",
CreditCard: CreditCard{Number: 123456, Company: Company{Name: "Bank A"}},
}
common.DB.Create(&user)
var retrivedUser User
var creditCard CreditCard
var company Company
common.DB.First(&retrivedUser, 1).Related(&creditCard).Related(&company)
fmt.Println("user name", retrivedUser.Name)
fmt.Println("creditcard number", retrivedUser.CreditCard.Number)
fmt.Println("creditcard number related", creditCard.Number)
fmt.Println("company name", retrivedUser.CreditCard.Company.Name)
fmt.Println("company name related", company.Name)
打印:
user name Alicecreditcard number 0
creditcard number related 123456
company name
company name related
两个问题:
- 为什么我需要选择
Related
creditCard作为单独的变量而不是使用点符号? - 我
invalid association []
在Related
公司上遇到错误,并且没有点符号或相关工作。我该如何取回?
回答:
根据文件,你需要设置auto_preload
以true
进行自动预加载工作。因此,将检索用户的行更改为:
common.DB.Set("gorm:auto_preload", true).First(&retrivedUser, 1)
应该给您预期的结果。
On a side note, ignore the errors. You can always append .Error
to
almost every operation in gorm
and check the returned error. For example:
err = common.DB.AutoMigrate(...).Errorif err != nil {
// handle err
}
err = common.DB.Create(&user).Error
// Check for err
err = common.DB.Set("gorm:auto_preload", true).First(&retrivedUser, 1).Error
// Check for err
以上是 使用GORM选择相关字段 的全部内容, 来源链接: utcz.com/qa/423658.html