Skip to content

Left joins with inline and optional relationships? #399

@cmoad

Description

@cmoad

I've referred to https://tour.upper.io/sql-builder/02 but the example doesn't show how to deal with optional relationships / left joins.

In this made up example, a parent has zero or more children and a child has exactly one parent. (Don't question it. Just go with it.) I want a query that grabs all children for a specific parent.

type Parent struct {
  ID int64 `db:"id"`
}

type Child struct {
  ID int64 `db:"id"`
  ParentID int64 `db:"parent_id"
}

type ParentChild struct {
  ParentID `db:"pid"`
  Parent `db:",inline"`
  Child `db:",inline"`
}

q := sess.Select("parent.id AS pid", "*").
  From("parent").LeftJoin("children").On("parent.id = child.parent_id").
  Where("parent.id = 1")

I'll always get back one or more rows (assuming there is a parent with id = 1), but I can't figure out how to scan into the inline Child without getting an error like:

panic: sql: Scan error on column index N: converting driver.Value type <nil> ("<nil>") to a int64: invalid syntax

Is there a clean way to handle this without writing a completely new struct for Child that supports null types?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions