mgutz / dat

Go Postgres Data Access Toolkit
Other
610 stars 62 forks source link

Querying nested JSON with SelectDoc #44

Open blasterpistol opened 8 years ago

blasterpistol commented 8 years ago

First of all, thank you for this great library.

But I have encountered one problem. Dat cannot populate nested json with single trip to Postgres.

I have some nested structs (simplified):

type Item struct {
    ID          int             `db:"id" json:"id"`
    Name        string          `db:"name" json:"name"`
    CatalogPart ItemCatalogPart `json:"catalog_part"`
}

type ItemCatalogPart struct {
    Description string      `db:"description" json:"description"`
    Fields      []ItemField     `json:"fields"`
}

type ItemField struct {
    ID           int    `db:"id" json:"id"`
    Value        string `db:"value" json:"value"`
}

And I trying to query Item with SelectDoc:

func (repo *DBItemRepo) FindByID(id int) (item domain.Item) {
    repo.dbHandler.
        SelectDoc("id", "name").
        One("catalog_part", "SELECT description FROM items AS i WHERE i.id = items.id").
        Many("fields", "SELECT id, value FROM item_fields WHERE item_id = items.id ORDER BY id").
        From("items").
        Where("id = $1", id).
        QueryStruct(&item)
    return
}

Of course I get nil. How to do it with one trip to DB? Thank you.

mgutz commented 8 years ago

Try using pointers to ItemCatalogPart and ItemPart? What you're doing is how we use dat in our project. I'll try to find some time later this week if that doesn't work.