Circular Reference in Schema Relation

I'm trying the following:
export const pages = pgTable("pages", {
...shared,
// primaryMetadataId: uuid()
// .unique()
// .references(() => metadata.id, { onDelete: "cascade" }),
});

export const metadata = pgTable("metadata", {
...shared,
pageId: uuid()
.notNull()
.references(() => pages.id, { onDelete: "cascade" }),
});
export const pages = pgTable("pages", {
...shared,
// primaryMetadataId: uuid()
// .unique()
// .references(() => metadata.id, { onDelete: "cascade" }),
});

export const metadata = pgTable("metadata", {
...shared,
pageId: uuid()
.notNull()
.references(() => pages.id, { onDelete: "cascade" }),
});
As soon as I uncomment the primaryMetadataId, I get a bunch of typescript errors. In this case every metadata should belong to a page but the page may select one as "primary". I believe this could be done with a join table, but I'd rather just have the schema clean
8 Replies
nahtnam
nahtnamOP3mo ago
Prisma allows this like this
model Page {
id String @id @default(cuid())

metadata Metadata[] @relation(name: "PageMetadata")
primaryMetadataId String? @unique
primaryMetadata Metadata? @relation(name: "PrimaryPageMetadata", fields: [primaryMetadataId], references: [id], onDelete: Cascade)
}

model Metadata {
id String @id @default(cuid())

pageId String
page Page @relation(name: "PageMetadata", fields: [pageId], references: [id], onDelete: Cascade)
primaryPage Page? @relation(name: "PrimaryPageMetadata")
}
model Page {
id String @id @default(cuid())

metadata Metadata[] @relation(name: "PageMetadata")
primaryMetadataId String? @unique
primaryMetadata Metadata? @relation(name: "PrimaryPageMetadata", fields: [primaryMetadataId], references: [id], onDelete: Cascade)
}

model Metadata {
id String @id @default(cuid())

pageId String
page Page @relation(name: "PageMetadata", fields: [pageId], references: [id], onDelete: Cascade)
primaryPage Page? @relation(name: "PrimaryPageMetadata")
}
rphlmr ⚡
rphlmr ⚡3mo ago
You need to type the references(():AnyPgColumn => ...)
rphlmr ⚡
rphlmr ⚡3mo ago
that's a typescript issue :/
nahtnam
nahtnamOP3mo ago
Thank you very much!!! Is this documented anywhere?
patrick
patrick2mo ago
did you get this to work with those onDelete: "cascades" in there? I am failing to get that to work!
nahtnam
nahtnamOP2mo ago
Yes it worked for me What issue are you having?
patrick
patrick2mo ago
drizzle migrate tool fails with TypeError: Cannot read properties of undefined (reading 'id') at mytable.myfield.references.onDelete seems to be related to the order esm modules are getting evaluated. i have a circular reference between two pgTables in two modules, and now none of my other tables can refer to one of those two in the circle without migrate failing.

Did you find this page helpful?