Scanning one-to-many relations/join queries

I’m delving into Go programming, and I’m seeing lots of articles why to stay away from the “orm” libraries for go and just write the sql yourself. While I have no problem with this philosophy and I feel adequate in sql to deal with writing my own queries and whatnot, I’m struggling to come to terms with how I would scan a join into a struct that has a one to many relationship.

Let’s say for instance I have two classes: Author and Book. And they have their typical respective columns, and Book has a column authorID to show who wrote it. Then let’s say I want to get the author with all the books they’ve written so I write the typical join query to select the author and books where book.authorId = authorId. How would I go about scanning something like this into a struct? Here’s the example structs:

type Author struct {
    ID int
    Name string
    Books []Book
}

type Book struct {
    ID int
    Title string
    AuthorID int
}

Or am I over thinking things and just need to not fret about joins and just use multiple queries?

1 Like

While I agree with staying away from ORM, I will confess that the current SQL libraries out there are pretty abysmal when it comes to scanning data directly into structs. Using a library like sqlx will help make this easier, but only marginally.

I think the general feeling from the Go community is, if you can get the query running, you can feed this struct manually yourself. :confused:

…not fret about joins and just use multiple queries?

I’d choose this approach.

  1. That’s exactly what you want: (a) One Author (-> query 1), (b) All books of that author (-> query 2). Done.
  2. I see no advantage from using a join for this use case. You would save one query (which would be fast anyway if the Name column is indexed and if the query uses no leading wildcard), but you would get the author’s name and ID replicated in every record of the result set (although you need the author info exactly once (for filling the Author struct)).

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.