Skip to Content

One-to-One

Here is an example of a one-to-one relation, make sure to always add the relations defininition following the reference fields:

// contactInformation.ts export const contactInformation = pgTable('contact_information', { id: serial('id').primaryKey(), serviceOrderId: varchar('service_order_id') // Here we define the relation with the .notNull() // serviceOrder table, using the serviceOrder .references(() => serviceOrder.id), // id as the foreign key // ...rest of the fields }) export const constactInformationRelations = relations(contactInformation, ({ one }) => ({ serviceOrder: one(serviceOrder, { fields: [contactInformation.serviceOrderId], references: [serviceOrder.id], relationName: 'createdBy', }), })) /* In the service order table we dont't need to set the relation for the contact information because we did it in the contact information. But we do need to set the relation to the contact in Drizzle's relation definitions Here is the example: */ export const serviceOrderRelations = relations(serviceOrder, ({ many, one }) => ({ // ... All other relations contactInformation: one(contactInformation), }))

One-to-Many

Here is an example of a one-to-many relation, make sure to always add the relations defininition following the reference fields:

export const serviceOrderStatus = pgTable('service_order_status', { id: serial('id').primaryKey().notNull(), serviceOrderId: varchar('service_order_id') // Here we define the "many" side of the relation by .references(() => serviceOrder.id) // setting the serviceOrderId field as a foreign key, our "one" .notNull(), // side. // ... all other fields }) // Now on the serviceOrder table we need to set the relation to the serviceOrderStatus table // in Drizzle's relation definitions. export const serviceOrderRelations = relations(serviceOrder, ({ many }) => ({ historicStatus: many(serviceOrderStatus), }))
Last updated on