You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 11:45:06