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

如何让Drizzle ORM推断Schema类型时包含关联关系?

在Drizzle ORM中让InferModel包含关联关系类型的方法

Drizzle ORM的InferModel默认只生成表列对应的类型,不会自动关联relations中定义的关联类型。你可以用以下两种更简洁的方式替代手动合并类型:

方法1:使用Relations类型自动提取关联(推荐)

Drizzle v0.28及以上版本提供了Relations类型,可以直接从你的关系定义中提取关联的类型,无需手动声明:

首先导入Relations类型:

import { relations, type InferModel, type Relations } from "drizzle-orm";
import { integer, pgTable, primaryKey } from "drizzle-orm/pg-core";

import { privileges } from "@config/db/schema/privilege";
import { roles, type Role } from "@config/db/schema/role";

然后定义包含关联的类型:

export const rolePrivileges = pgTable("role_privileges", {
   roleId: integer("role_id").notNull().references(() => roles.id, { onDelete: "cascade" }),
   privilege: privileges("privilege")
}, (rolePrivileges) => ({
   pk: primaryKey(rolePrivileges.roleId, rolePrivileges.privilege)
}))

export const rolePrivilegesRelations = relations(rolePrivileges, ({ one }) => ({
   role: one(roles, {
      fields: [rolePrivileges.roleId],
      references: [roles.id]
   })
}))

// 自动合并表列类型和关联类型
export type RolePrivilege = InferModel<typeof rolePrivileges> & Relations<typeof rolePrivilegesRelations>;

这种方式的优势是:后续如果在rolePrivilegesRelations中添加或修改关联,RolePrivilege类型会自动同步更新,不需要手动维护关联字段的类型。

方法2:从查询结果中提取类型

如果你的需求是针对特定查询场景的返回类型,可以直接从关联查询的结果中提取类型:

// 示例查询:关联查询rolePrivileges和对应的role
const rolePrivilegeWithRole = await db.query.rolePrivileges.findFirst({
  with: { role: true }
});

// 直接提取查询结果的类型
export type RolePrivilege = typeof rolePrivilegeWithRole;

这种方式适合需要严格匹配查询返回结构的场景,但类型依赖于具体的查询逻辑。


内容的提问来源于stack exchange,提问作者alas.code

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 04:35:15