`{ onDelete: "cascade" }` when the entity is in one-to-one relationship with multiple entities?

hey guys,

whats the best way to use { onDelete: "cascade" } when the entity is in one-to-one relationship with multiple entities?

I have a users, friendRequests and locations.

users, friendRequests both have a location, and if a user or friendRequests gets deleted, I want to delete the corresponding location as well.

export const users = pgTable(
  "users",
  {
    id: text("id")
    .primaryKey()
    locationId: text("locationId").references(() => locations.id),
  },
);

export const usersRelations = relations(users, ({ one }) => ({
  location: one(locations, {
    fields: [users.locationId],
    references: [locations.id],
  }),
}));

export const friendRequests = pgTable(
  "friendRequests",
  {
    sentById: text("sentById")
      .references(() => users.id, { onDelete: "cascade" }),
    receivedById: text("receivedById")
      .references(() => users.id, { onDelete: "cascade" }),
    locationId: text("locationId").references(() => locations.id),
  },
  (table) => ({
    pk: primaryKey(table.sentById, table.receivedById),
    sentBy: index("friendRequests_sentBy_idx").on(table.sentById),
    receivedBy: index("friendRequests_receivedBy_idx").on(table.receivedById),
  })
);

export const friendRequestsRelations = relations(friendRequests, ({ one }) => ({
  sentBy: one(users, {
    fields: [friendRequests.sentById],
    references: [users.id],
    relationName: RELATION_NAMES.FRIEND_REQ_SENT,
  }),
  receivedBy: one(users, {
    fields: [friendRequests.receivedById],
    references: [users.id],
    relationName: RELATION_NAMES.FRIEND_REQ_RECEIVED,
  }),
  location: one(locations, {
    fields: [friendRequests.locationId],
    references: [locations.id],
  }),
}));

export const locations = pgTable("location", {
  id: text("id")
    .primaryKey()
  lat: doublePrecision("lat").notNull(),
  lng: doublePrecision("lng").notNull(),
});
Was this page helpful?