Reputation: 195
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
}
Upvotes: 18
Views: 36994
Reputation: 59
//items schema this is how I am exporting types of items schema
export type Item = typeof items.$inferSelect;
Upvotes: 5
Reputation: 499
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.
Upvotes: 13
Reputation: 176
I was recently looking into the same thing and judging from the Discord answers I've seen, I'm pretty sure that's the current strategy to combine them (and what I am currently implementing in my project).
It's on their radar tho - here's a link to the backlog request for this feature: https://github.com/drizzle-team/drizzle-orm/issues/695
Upvotes: 11