Hey folks!
I'm a junior web dev used to working in the python/Django space. I'm super interested in Go and am currently working on a simple web-based directory project to try and get a bit of experience with the language.
My first major hurdle is moving from the extremely magic heavy ORM model to a more "raw" way of working with the database.
Let's say I have the following structs:
type Location struct {
ID uint64
Name string
}
type Person struct {
ID uint64
FirstName string
LastName string
}
and Person has-a Location. What is the most idiomatic way to link these models? I've read about embedding anonymous structs, but it's not quite clear to me how to set these up.
Thanks in advance and if I can clarify I'm happy to post more code/info
评论:
adelowo:
ChristophBerger:Struct embedding is the way to go.. At the barest level, it is just "inheritance"..
As far as I know, sqlx can do this... You tell sqlx to map the relationship on "loading from the db" by struct tags (reflection ish)..
So basically, you convert your person struct to this
type Person struct { ID uint64 `db:"id"` FirstName string `db:"first_name"` LastName string `db:"last_name"` Location Location `db:"location"` }
Edit --> I forgot to mention you have to make use of
StructScan
to get the data into theUser
StructEdit -> /u/ChristophBerger has a link to what embedding really is
timberwolf5922:Agreed, this would be the usual way of linking a location to a person (in case of a 1-1 relationship).
Just one minor side node: The term "embedding" is usually only used for anonymous fields, sometimes also called embedded fileds. The Location field above is just a normal field in a struct.
ChristophBerger:Just wanted to follow up here: Is the above (Location as a field on Person) only useful for 1-1? The relationship I'm trying to represent is many-to-one (Many Person structs can have the same Location)
adelowo:Sorry, my fault. You are right, it is of course an M-1 relationship between Person and Location.
Wrathbun:Thanks for the correction.
adelowo:Another noob here, Ive been struggling with this as well. Struct embedding seems to be the recommended option but it feels kinda hacky to me to represent database relationships this way? Is there any alternative patterns for this?
Also just to clarify, using OPs example, if I have a "location_id" foreign key on my person table, is sqlx smart enough to unmarshall "location_id" into the id field on the Location embedded struct even though it has the same db struct tag as the id field on the Person struct?
:Yes, the id would be correctly set on the
Location
struct.. I don't know of anyother way around ths.
adelowo:[deleted]
adelowo:Thanks for the correction.
Thanks for the correction.
