一尘不染

使用GORM选择相关字段

go

我是来自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 Alice
creditcard number 0
creditcard number related 123456
company name 
company name related

两个问题:

  1. 为什么我需要选择RelatedcreditCard作为单独的变量而不是使用点符号?
  2. invalid association []Related公司上遇到错误,并且没有点符号或相关工作。我该如何取回?

阅读 684

收藏
2020-07-02

共1个答案

一尘不染

根据文件,你需要设置auto_preloadtrue进行自动预加载工作。因此,将检索用户的行更改为:

common.DB.Set("gorm:auto_preload", true).First(&retrivedUser, 1)

应该给您预期的结果。


On a side note, never 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(...).Error
if 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
2020-07-02