How can I do a join query for the sole purpose of filtering?

Essentially my question is how can I do this better in drizzle.
const myTeams = await ctx.db
.select()
.from(teams)
.innerJoin(
members,
and(eq(members.teamId, teams.id), eq(members.userId, ctx.user.id)),
);

return myTeams.map((t) => t.team);
const myTeams = await ctx.db
.select()
.from(teams)
.innerJoin(
members,
and(eq(members.teamId, teams.id), eq(members.userId, ctx.user.id)),
);

return myTeams.map((t) => t.team);
I really want to just write
SELECT T.*
FROM teams T, members M
WHERE T.id = M.teamId
AND M.userId = ?
SELECT T.*
FROM teams T, members M
WHERE T.id = M.teamId
AND M.userId = ?
11 Replies
KiKo
KiKoOP14mo ago
is this multiple tables with from a thing in drizzle?
Angelelz
Angelelz14mo ago
Drizzle doesn't support selecting from multiple tables yet. You'll need to use a join You can select only from the table that you need.
KiKo
KiKoOP13mo ago
How would you rewrite this to do the same thing in a drizzle friendly way, this is how I was taught in school... also is there a shorthand to return only the properties on teams and avoid the .map? I know I could write out all of the properties manually
Angelelz
Angelelz13mo ago
You can select whatever you want https://orm.drizzle.team/docs/select
SQL Select - Drizzle ORM
Drizzle ORM is a lightweight and performant TypeScript ORM with developer experience in mind.
Angelelz
Angelelz13mo ago
You already have the query written, is the innerJoin query that you have, isn't it?
KiKo
KiKoOP13mo ago
is the innerjoin the best way to do it? that's what I ultimately landed on but is there a correct way to do it also I dont see anything in the docs that includes a team.* select for example
Angelelz
Angelelz13mo ago
You could do a subquery, but in terms of what's better, you'll need to evaluate with some tests I guess There's no team.* but there's getTableColumns() helper function that will get you something equivalent
Angelelz
Angelelz13mo ago
Goodies - Drizzle ORM
Drizzle ORM is a lightweight and performant TypeScript ORM with developer experience in mind.
KiKo
KiKoOP13mo ago
That looks good thanks is there a plan to support multiple tables in the future? or is that a task too difficult for typescript
Angelelz
Angelelz13mo ago
I don't know about the plan, but usually the join is the canonical way of joining tables It's what relational dbs do IMO, using a subquery could even read better:
db.select()
.from(teams)
.where(
inArray(teams.id, db
.select({ teamId: members.teamId })
.from(members)
.where(eq(members.userId, ctx.user.id))
)
db.select()
.from(teams)
.where(
inArray(teams.id, db
.select({ teamId: members.teamId })
.from(members)
.where(eq(members.userId, ctx.user.id))
)
KiKo
KiKoOP13mo ago
ahhh, thats cool Thank you very much
Want results from more Discord servers?
Add your server