Filter query by column in joined table #891
-
|
I have a simple data model: dogs and humans. SELECT h.name, d.name
FROM dogs d
JOIN humans h ON h.id = d.owner_id
WHERE h.name = 'Kevin'I'm wondering if this is possible using eager loading, but ultimately eager loading is not necessary. Ideally, I'd like to avoid raw SQL, and I'd like to avoid writing out all columns in my query. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
|
Here's what I've come up with: dogs, err := models.Dogs(
// eager load the dog's hooman
qm.Load(models.DogRels.Human,
qm.Where(fmt.Sprintf("%s.%s = ?", models.TableNames.Humans, models.HumanColumns.Name), humanNames[0]),
),
qm.Limit(5),
).All(ctx, exec)The |
Beta Was this translation helpful? Give feedback.
-
|
Using an func queryForDogs() {
dogs, err := models.Dogs(
// eager load the dog's hooman
qm.Load(models.DogRels.Human),
qm.InnerJoin(
fmt.Sprintf(
"%s on %s.%s = %s.%s",
models.TableNames.Humans,
models.TableNames.Humans,
models.HumanColumns.ID,
models.TableNames.Dogs,
models.DogColumns.HumanID,
),
),
qm.Where(
fmt.Sprintf(
"%s.%s = ?",
models.TableNames.Humans,
models.HumanColumns.Name,
),
humanNames[0],
),
qm.Limit(5),
).All(ctx, exec)
} |
Beta Was this translation helpful? Give feedback.
Using an
InnerJoinmeans we filter out the records that don't match ourWHEREcriteria.