Unable to delete from many to many relationship due to FK constraint

I have the following schema,

Users <> Teams
  • many to many
    usersOnTeams - table to hold this relationship
m currently unable to delete a Team record due to the foreign key of the team still existing in the usersOnTeams table record.
I know it has something to do with cascading deletes but I'm not sure how. Any help is appreciated.

// USER
export const users = pgTable('users', {
  id: uuid('id').defaultRandom().primaryKey(),
  clerkId: text('user_id').notNull().unique(),
  email: text('email').notNull(),
  firstName: text('first_name'),
  lastName: text('last_name'),
  avatarUrl: text('avatar_url'),
  createdAt: timestamp('created_at').notNull().defaultNow(),
})

export const usersRelation = relations(users, ({ many }) => ({
  usersToTeams: many(usersOnTeams),
  videos: many(videos),
  uploads: many(uploads),
  cuepoints: many(cuepoints),
}))

// TEAM
export const teams = pgTable('teams', {
  id: uuid('id').defaultRandom().primaryKey(),
  clerkId: text('org_id').notNull().unique(),
  name: text('name').notNull(),
  slug: text('slug').notNull(),
  createdAt: timestamp('created_at').notNull().defaultNow(),
  logo: text('logo'),
})

export const teamsRelation = relations(teams, ({ many }) => ({
  usersToTeams: many(usersOnTeams),
  videos: many(videos),
}))

// USERSONTEAMS
export const usersOnTeams = pgTable(
  'usersOnTeams',
  {
    userId: text('user_id')
      .notNull()
      .references(() => users.clerkId),
    teamId: text('team_id')
      .notNull()
      .references(() => teams.clerkId),
  },
  (t) => ({
    pk: primaryKey(t.userId, t.teamId),
  })
)

export const usersOnTeamsRelations = relations(usersOnTeams, ({ one }) => ({
  user: one(users, {
    fields: [usersOnTeams.userId],
    references: [users.clerkId],
  }),
  team: one(teams, {
    fields: [usersOnTeams.teamId],
    references: [teams.clerkId],
  }),
}))
Was this page helpful?