dqyhj2014 2019-04-22 09:39
浏览 659
已采纳

使用GORM选择相关字段

I'm new to Golang coming from a python background so trying to understand the new and different concepts. I'm trying to create related fields and then select them from the database.

Models:

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
}

Create tables and rows and select from db

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)

This prints:

user name Alice
creditcard number 0
creditcard number related 123456
company name 
company name related 

Two questions:

  1. Why do I need to select Related creditCard to a separate variable instead of using the dot notation?
  2. I get error invalid association [] on the Related company, and neither dot notation or Related work. How do I get this back?
  • 写回答

1条回答 默认 最新

  • douzhenchun6782 2019-04-22 10:34
    关注

    According to documentation, you need to set auto_preload to true for Auto Preloading to work. So changing the line where you retrieve the user to:

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

    should give you the expected result.


    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么