How to use cascade with a multi-column foreign key?

When using references I can tell a foreign key to cascade on a delete easily. However: I have a table with a composite primary key:
const items = pgTable(
'items',
{
id: integer('id').notNull(),
hotelId: integer('hotel_id')
.references(() => hotels.id, CASCADE)
.notNull(),
// ...other fields
},
(table) => ({
pk: primaryKey(table.id, table.hotelId)
})
);
const items = pgTable(
'items',
{
id: integer('id').notNull(),
hotelId: integer('hotel_id')
.references(() => hotels.id, CASCADE)
.notNull(),
// ...other fields
},
(table) => ({
pk: primaryKey(table.id, table.hotelId)
})
);
and a table referencing that table with a composite foreign key:
const addresses = pgTable(
'client_item_addresses',
{
itemId: integer('item_id').notNull(),
hotelId: integer('hotel_id').notNull(),
// ...other fields
},
(table) => ({
pk: primaryKey(table.itemId, table.hotelId),
fk: foreignKey({
columns: [table.itemId, table.hotelId],
foreignColumns: [items.id, items.hotelId]
})
})
);
const addresses = pgTable(
'client_item_addresses',
{
itemId: integer('item_id').notNull(),
hotelId: integer('hotel_id').notNull(),
// ...other fields
},
(table) => ({
pk: primaryKey(table.itemId, table.hotelId),
fk: foreignKey({
columns: [table.itemId, table.hotelId],
foreignColumns: [items.id, items.hotelId]
})
})
);
How do I activate cascade on delete in this scenario?
7 Replies
Andrii Sherman
Andrii Sherman10mo ago
oh, that's a nice feature request we don't have this option now and should definitely add it
Schred
Schred10mo ago
I see, no problem! Haven't had a look at the codebase yet, but do you think this would be a doable first contribution?
Angelelz
Angelelz10mo ago
This is an easy one because the underlying class already supports it. You just need to accept the parameter in the function. This a nice first contribution
Schred
Schred10mo ago
Alright thanks, I'll see what I can do then ^^
Hocus
Hocus10mo ago
oh, I think I literally just ran into the same issue ... I think? https://discord.com/channels/1043890932593987624/1183062166690082826/1183062166690082826
WavyBoyJodii
WavyBoyJodii9mo ago
yes, this functionality is needed asap Pog
Schred
Schred9mo ago
GitHub
feat: Add actions to foreignKey(...) by cegredev · Pull Request #16...
Changed: Added parameter actions to function foreignKey in foreign-keys.ts for postgres, mysql and mysql-lite which allows for onUpdate and onDelete actions when using multi-column foreign keys. Ex...
Want results from more Discord servers?
Add your server