How to define type of table with all relations included?

Say I have a a table users and a user has many posts, so I define a relationship as shown in the docs If I want to define a type that is "user with posts" that would be the result of:
await db.query.user.findFirst({ with: { posts: true } });
await db.query.user.findFirst({ with: { posts: true } });
the type of this would be something like
type UserWithPosts = (typeof users._.inferSelect) & {posts: Array<typeof posts._.inferSelect>}
type UserWithPosts = (typeof users._.inferSelect) & {posts: Array<typeof posts._.inferSelect>}
Is there a cleaner way to define that where all the relations are just included and automatically inferred?
4 Replies
jakeleventhal
jakeleventhal6mo ago
or if you had a one-to-one relationship (for instance the user has one "post"), then the type would be even more complicated:
type UserWithPosts = (typeof users._.inferSelect) & {post: typeof posts._.inferSelect | null}
type UserWithPosts = (typeof users._.inferSelect) & {post: typeof posts._.inferSelect | null}
Angelelz
Angelelz6mo ago
Yes, this is a way you can currently define the types
Angelelz
Angelelz6mo ago
I have an open PR for a couple helpers https://github.com/drizzle-team/drizzle-orm/pull/1670. Waiting for the approval of the team
GitHub
Build software better, together
GitHub is where people build software. More than 100 million people use GitHub to discover, fork, and contribute to over 420 million projects.
jakeleventhal
jakeleventhal6mo ago
nice work, subscribed to the PR