© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
Drizzle TeamDT
Drizzle Team•14mo ago•
3 replies
N

Self referencing composite primary key table

I'm trying to define a table where each organization can define a parent-child set of locations. Each location has a composite primary key (org, id) but i can't seem to get the self referencing foreign keys to work. Is there a way to accomplish what i'm trying to do? here's my code. Thanks!
export const locations = pgTable(
  'locations',
  {
    id: varchar('id', { length: 60 }).notNull(),
    orgId: varchar('org_id', { length: 60 }).notNull(),
    name: varchar('name', { length: 255 }).notNull(),
    isLeaf: boolean('is_leaf').default(false).notNull(),
    parentId: varchar('parent_id', { length: 60 }),
    parentOrgId: varchar('parent_org_id', { length: 60 }),
  },
  (table) => ({
    pk: primaryKey({
      columns: [table.id, table.orgId],
      name: 'locations_pkey'
    }),
  }),
);

export const locationsRelations = relations(locations, ({ many, one }) => ({
  parent: one(locations, {
    fields: [locations.parentId, locations.parentOrgId],
    references: [locations.id, locations.orgId],
    relationName: 'parent_child',
  }),
  children: many(locations, {
    relationName: 'parent_child',
  }),
}));
export const locations = pgTable(
  'locations',
  {
    id: varchar('id', { length: 60 }).notNull(),
    orgId: varchar('org_id', { length: 60 }).notNull(),
    name: varchar('name', { length: 255 }).notNull(),
    isLeaf: boolean('is_leaf').default(false).notNull(),
    parentId: varchar('parent_id', { length: 60 }),
    parentOrgId: varchar('parent_org_id', { length: 60 }),
  },
  (table) => ({
    pk: primaryKey({
      columns: [table.id, table.orgId],
      name: 'locations_pkey'
    }),
  }),
);

export const locationsRelations = relations(locations, ({ many, one }) => ({
  parent: one(locations, {
    fields: [locations.parentId, locations.parentOrgId],
    references: [locations.id, locations.orgId],
    relationName: 'parent_child',
  }),
  children: many(locations, {
    relationName: 'parent_child',
  }),
}));
Drizzle TeamJoin
The official Discord for all Drizzle related projects, such as Drizzle ORM, Drizzle Kit, Drizzle Studio and more!
11,879Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Composite Primary Key?
Drizzle TeamDTDrizzle Team / help
16mo ago
reference composite primary key
Drizzle TeamDTDrizzle Team / help
3y ago
Composite primary key, multiple primary keys
Drizzle TeamDTDrizzle Team / help
2y ago
Compostie primary key of a composite primary key
Drizzle TeamDTDrizzle Team / help
2y ago