Kyle
Kyle•11mo ago

Example Utility for Joining between Tables

Made a fun little helper for joining tables: https://gist.github.com/kyldvs/98aed78f96e9376b55092493a8bb0b75
// This has { _id: Id<"orgRole">, orgId: Id<"org">, ... }
const roles = await ctx.db.query("orgRole").collect();

// This has { _id: Id<"orgRole">, org: Doc<"org"> | undefined, ... }
const rolesWithOrg = await join<"orgRole", "org">(ctx.db, roles, "orgId");
// This has { _id: Id<"orgRole">, orgId: Id<"org">, ... }
const roles = await ctx.db.query("orgRole").collect();

// This has { _id: Id<"orgRole">, org: Doc<"org"> | undefined, ... }
const rolesWithOrg = await join<"orgRole", "org">(ctx.db, roles, "orgId");
Based on: https://docs.convex.dev/database/reading-data#join
Gist
join on fields between convex tables
join on fields between convex tables. GitHub Gist: instantly share code, notes, and snippets.
2 Replies
Kyle
KyleOP•11mo ago
@ian here's the post; I think you're right about being able to get rid of the the type params. I tried to do it by leveraging the field that's provided and mapping it to the JoinTable type, and then you have the items for the BaseTable type, but something wasn't quite working so I forced them to be provided and moved on 🙂 The other improvement I noticed is if the id field doesn't map to the table names it breaks down. i.e. if you have authorId which points to a user instead of a userId then the mapping won't find Doc<"author">, it should be looking for Doc<"user">. (And similar issue if you use plural table name convention instead of singular)
ian
ian•11mo ago
I have been thinking through some similar ergonomics for my helpers. I recorded a video recently about some tricks for this, that is currently being edited. One thing I do is to have an optional argument at the end that is only optional if the name doesn't match. In my case it's comparing the index name to the field name. There some other type utilities there too covered in this Stack post. https://github.com/get-convex/convex-helpers/blob/main/packages/convex-helpers/server/relationships.ts
GitHub
convex-helpers/packages/convex-helpers/server/relationships.ts at m...
A collection of useful code to complement the official packages. - get-convex/convex-helpers

Did you find this page helpful?