如何获取Drizzle-ORM关联查询(Join)的返回类型?
获取Drizzle-ORM关联查询的返回类型
以下是我的Drizzle-ORM schema代码:
export const user = pgTable('users', { id: serial("id").primaryKey(), createdAt: timestamp("created_at").defaultNow(), updatedAt: timestamp("updated_at").$onUpdate(() => new Date()), name: varchar("name").notNull() }); export const post = pgTable('posts', { id: serial("id").primaryKey(), createdAt: timestamp("created_at").defaultNow(), updatedAt: timestamp("updated_at").$onUpdate(() => new Date()), title: varchar("title").notNull(), userId: integer("user_id").notNull().references(() => user.id) }); export type AddUser = typeof user.$inferInsert; export type GetUser = typeof user.$inferSelect; export type AddPost = typeof post.$inferInsert; export type GetPost = typeof post.$inferSelect; export const userRelations = relations(user, ({ many }) => ({ posts: many(post), })); export const postRelations = relations(post, ({ one }) => ({ user: one(user, { fields: [post.userId], references: [user.id], }), }));
请问如何获取如下关联查询的返回类型?
const usersWithPost = await db.query.user.findMany({ with: { posts: true, } });
方法一:通过typeof直接推导
最简单的方式是利用TypeScript的typeof操作符,从查询结果变量提取类型:
type UsersWithPosts = typeof usersWithPost;
如果需要提前定义类型(不依赖实际变量),可以基于查询方法的返回类型推导:
type UsersWithPosts = Awaited<ReturnType<typeof db.query.user.findMany<{ with: { posts: true } }>>>;
方法二:使用Drizzle的InferSelectModel工具类型
从drizzle-orm导入InferSelectModel后,可以结合表和关系定义类型,无需依赖查询变量:
import { InferSelectModel } from "drizzle-orm"; type UsersWithPosts = InferSelectModel<typeof user, { relations: { posts: true; } }>;
这种方式适合在函数参数、返回值等场景中提前声明类型。
内容的提问来源于stack exchange,提问作者xargr
相关产品推荐
相关产品推荐

