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:
- Why do I need to select
Related
creditCard to a separate variable instead of using the dot notation? - I get error
invalid association []
on theRelated
company, and neither dot notation or Related work. How do I get this back?