You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
package storage
type Country struct {
ID string `json:"id" gorm:"type:uuid"`
Name string `json:"name"`
Code string `json:"code"`
}
type City struct {
ID string `json:"id" gorm:"type:uuid"`
Name string `json:"name"`
Code *string `json:"code"`
CountryId string `json:"country_id"`
Country *Country `json:"country" gorm:"references:ID"`
IATA *string `json:"iata"`
Latitude *string `json:"latitude"`
Longitude *string `json:"longitude"`
}
The city should have a pointer to a Country model to make it easier to understand whether Country has been joined (in sql) or not (e.g. if city.Country == nil {panic("for whatever reason")} )
The problem appears when I try to get the list of all cities:
package example
var cities []storage.City
tx.Joins("Country").Find(&cities)
Here, all the cities have been fetched from DB nicely, but the countries became the same in all the cities.
If I print out cities I get the following:
Please pay attention to Country field of the outputs. In the ACTUAL OUTPUT all the cities have the same country. I think this has something to do with the pointer.
I got EXPECTED OUTPUT when I removedthepointer from Country (so *Country became Country without *). But I would like to get the same output with the pointer (*Country).
Also, please do not pay attention to the values printed out in other fields. My main focus is the Country field.
The document you expected this should be explained
Your Question
Suppose you have database models as follows:
The city should have a pointer to a Country model to make it easier to understand whether Country has been joined (in sql) or not (e.g.
if city.Country == nil {panic("for whatever reason")}
)The problem appears when I try to get the list of all cities:
Here, all the cities have been fetched from DB nicely, but the countries became the same in all the cities.
If I print out
cities
I get the following:Please pay attention to Country field of the outputs. In the ACTUAL OUTPUT all the cities have the same country. I think this has something to do with the pointer.
I got EXPECTED OUTPUT when I removed the pointer from Country (so
*Country
becameCountry
without*
). But I would like to get the same output with the pointer (*Country
).Also, please do not pay attention to the values printed out in other fields. My main focus is the Country field.
The document you expected this should be explained
Expected answer
What I expected to get is:
The text was updated successfully, but these errors were encountered: