canonical / sqlair

Friendly type mapping for SQL databases
Apache License 2.0
16 stars 8 forks source link

How do joins work? #152

Closed cpg1111 closed 2 weeks ago

cpg1111 commented 1 month ago

Say I have a struct nested in another struct like so:

type ModelA struct {
    ID int64 `db:"id,omitempty"`
    B []ModelB
}

type ModelB struct {
    ID int64 `db:"id,omitempty"`
    AID int64 `db:"a_id"`
}

And the following corresponding tables with a 1:many relation

Table A
|id |
| 1 |

Table B
|id |a_id|
| 1 | 1    |
| 2 | 1    |

Would the correct query syntax be the following? SELECT &ModelA.*, &ModelB.* FROM A as a JOIN B as b ON b.a_id = a.id;

Additionally, can various join examples be added to example_test.go for reference?

Aflynn50 commented 2 weeks ago

Unlike an ORM, SQLair does not preserve the nested structure of joins. In fact, SQLair does not even parse the fact that there is a JOIN in your query. It simply maps the outputs to the go structs.

So if you did a GetAll on the query above you would just end up with:

[]ModelA{{ID:1},{ID: 1}}
[]ModelB{{ID: 1, AID: 1}, {ID: 2, AID: 1}}

The nested structure would have to be reconstructed in your Go program.