I am working on an Express App which uses Drizzle as ORM connected to Postgres Database. When I Infered the type of a specific schema, only the declared columns are added as attributes of the generated type. Is it possible to include the type for the declared relations?
Here is the code for the scenario above:
import { relations, type InferModel } 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>
I tried to manually add the type for the relations by changing the value of type RolePrivilege to the code below and it worked, but I wanted to know if there is a more direct and less tedious way in doing so:
export type RolePrivilege = InferModel<typeof rolePrivileges> & {
role: Role
}
As of 0.28.3 (August 2022):
InferModel
is now deprecated in favour of InferSelectModel
and InferInsertModel
.
You can update your code as follows, depending on whether your use case for the type is selecting or inserting:
import { relations, type InferSelectModel } from "drizzle-orm"
...
export type RolePrivilege = InferSelectModel<typeof rolePrivileges> & {
role: Role
}
Please see the updated documentation for the Type API.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With