我是来自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
两个问题:
Related
invalid association []
根据文件,你需要设置auto_preload以true进行自动预加载工作。因此,将检索用户的行更改为:
auto_preload
true
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:
.Error
gorm
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