From 9ecc6c889929a07d1163919eac14c9b33b90208a Mon Sep 17 00:00:00 2001 From: Naoto Ikeno Date: Wed, 19 Jun 2024 22:52:11 +0900 Subject: [PATCH] fix(db-postgres): cascade delete FKs on hasMany relationships (#6735) ## Description This PR fixes https://github.com/payloadcms/payload/issues/6485. - [x] I have read and understand the [CONTRIBUTING.md](https://github.com/payloadcms/payload/blob/main/CONTRIBUTING.md) document in this repository. ## Type of change - [x] Bug fix (non-breaking change which fixes an issue) ## Checklist: - [x] I have added tests that prove my fix is effective or that my feature works - [x] Existing test suite passes locally with my changes --- .../db-postgres/src/schema/traverseFields.ts | 2 +- test/fields/int.spec.ts | 21 +++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/packages/db-postgres/src/schema/traverseFields.ts b/packages/db-postgres/src/schema/traverseFields.ts index b09d66e29ce..852d1a46c40 100644 --- a/packages/db-postgres/src/schema/traverseFields.ts +++ b/packages/db-postgres/src/schema/traverseFields.ts @@ -264,7 +264,7 @@ export const traverseFields = ({ name: `${selectTableName}_parent_fk`, columns: [cols.parent], foreignColumns: [adapter.tables[parentTableName].id], - }), + }).onDelete('cascade'), parentIdx: (cols) => index(`${selectTableName}_parent_idx`).on(cols.parent), } diff --git a/test/fields/int.spec.ts b/test/fields/int.spec.ts index c3854d64173..b83e33376db 100644 --- a/test/fields/int.spec.ts +++ b/test/fields/int.spec.ts @@ -37,6 +37,7 @@ import { tabsFieldsSlug, textFieldsSlug, } from './slugs' +import { NotFound } from '../../packages/payload/src/errors' let client: RESTClient let graphQLClient: GraphQLClient @@ -351,6 +352,26 @@ describe('Fields', () => { expect(updatedDoc.selectHasMany).toEqual(['one', 'two']) }) + // https://github.com/payloadcms/payload/issues/6485 + it('delete with selectHasMany relationship', async () => { + const { id } = await payload.create({ + collection: 'select-fields', + data: { + selectHasMany: ['one', 'two'], + }, + }) + await payload.delete({ + collection: 'select-fields', + id, + }) + await expect( + payload.findByID({ + collection: 'select-fields', + id, + }), + ).rejects.toThrow(NotFound) + }) + it('should query hasMany in', async () => { const hit = await payload.create({ collection: 'select-fields',