jsee
jsee
DTDrizzle Team
Created by jsee on 2/4/2024 in #help
Subqueries in relational queries
For posterity, I had tried something very similar to this, but didn't understand the syntax:
// this is incorrect
const sq = this.db
.select({ id: schema.authors.id })
.from(schema.authors)
.where(eq(schema.authors.name, "Some Name"))
.as("sq")

await db.query.posts.findMany({
where: (fields, ops) => ops.eq(fields.id, sq.id)
with: {
author: true,
},
});
// this is incorrect
const sq = this.db
.select({ id: schema.authors.id })
.from(schema.authors)
.where(eq(schema.authors.name, "Some Name"))
.as("sq")

await db.query.posts.findMany({
where: (fields, ops) => ops.eq(fields.id, sq.id)
with: {
author: true,
},
});
But the correct syntax is (note the lack of .as("sq") and the inArray operator:
const sq = this.db
.select({ id: schema.authors.id })
.from(schema.authors)
.where(eq(schema.authors.name, "Some Name"));

await db.query.posts.findMany({
where: (fields, ops) => ops.inArray(fields.id, sq)
with: {
author: true,
},
});
const sq = this.db
.select({ id: schema.authors.id })
.from(schema.authors)
.where(eq(schema.authors.name, "Some Name"));

await db.query.posts.findMany({
where: (fields, ops) => ops.inArray(fields.id, sq)
with: {
author: true,
},
});
Tried a few things around this but never got the right combination. Would be curious if anyone can explain a bit more about the difference there.
5 replies
DTDrizzle Team
Created by jsee on 2/4/2024 in #help
Subqueries in relational queries
5 replies