Repository navigation
Description
Describe the Bug
Hey first of all I've almost finished a production ready site with payloadcms thanks for open sourcing i think it's one of the best cmses I've ever used let me get to the issue currently there seems to be no way to set onUpdate or onDelete behaviors on relationships from collection configs meaning if you set a relationship to be required and try to delete the foreign key you will get this
[11:21:31] ERROR: null value in column "user_id" of relation "comments" violates not-null constraint
err: {
"type": "DatabaseError",
"message": "null value in column \"user_id\" of relation \"comments\" violates not-null constraint",
//removed unnecessary lines for readability How to reproduce ?
I will link the repo anyways but i don't think you need to reproduce it to understand whats wrong
Here is an example
src/collections/Comments.ts
import type { CollectionConfig } from 'payload'
import { authenticated } from '../../access/authenticated'
export const Comments: CollectionConfig = {
slug: 'comments',
access: {
admin: authenticated,
create: authenticated,
delete: authenticated,
read: authenticated,
update: authenticated,
},
fields: [
{
name: 'user',
type: 'relationship',
relationTo: 'users',
required: true,
//^important
},
{
name: 'content',
type: 'text',
required: true,
},
],
timestamps: true,
}Now try to delete the user of this comment and you will get the error
[11:21:31] ERROR: null value in column "user_id" of relation "comments" violates not-null constraint
err: {
"type": "DatabaseError",
"message": "null value in column "user_id" of relation "comments" violates not-null constraint",
//removed unnecessary lines for readability
Workaround for now
in payload.config.ts
db: postgresAdapter({
pool: {
connectionString: process.env.DATABASE_URI || '',
},
afterSchemaInit: [
({ schema }) => {
const relations = ['relations_comments']
relations.forEach((relation) => {
const index = Symbol.for(`drizzle:PgInlineForeignKeys`)
//@ts-expect-error workaround
const fkeys = schema.relations[relation].table[index]
// Loop through the foreign keys and modify them
//@ts-expect-error workaround
fkeys.forEach((foreignKey) => {
foreignKey.onDelete = 'CASCADE'
foreignKey.onUpdate = 'CASCADE'
})
})
return schema
},
],
}),Link to the code that reproduces this issue
Reproduction Steps
-create a user so you do not have to delete the admin user
-create a comment with user relation set to the newly created user
-try to delete the user it will fail
-uncomment the lines in payload.config.ts and restart the app
-try to delete now it will work
Which area(s) are affected? (Select all that apply)
area: core
Environment Info
Binaries:
Node: 20.11.1
npm: N/A
Yarn: N/A
pnpm: 9.6.0
Relevant Packages:
payload: 3.23.0
next: 15.1.7
@payloadcms/db-postgres: 3.23.0
@payloadcms/email-nodemailer: 3.23.0
@payloadcms/graphql: 3.23.0
@payloadcms/live-preview: 3.23.0
@payloadcms/live-preview-react: 3.23.0
@payloadcms/next/utilities: 3.23.0
@payloadcms/payload-cloud: 3.23.0
@payloadcms/plugin-form-builder: 3.23.0
@payloadcms/plugin-nested-docs: 3.23.0
@payloadcms/plugin-redirects: 3.23.0
@payloadcms/plugin-search: 3.23.0
@payloadcms/plugin-seo: 3.23.0
@payloadcms/richtext-lexical: 3.23.0
@payloadcms/translations: 3.23.0
@payloadcms/ui/shared: 3.23.0
react: 19.0.0
react-dom: 19.0.0
Operating System:
Platform: win32
Arch: x64
Version: Windows 11 Pro
Available memory (MB): 32678
Available CPU cores: 12
Activity
Saissaken commentedon Mar 5, 2025
I have a similar use case and found your workaround interesting. I ended up transforming it into a utility function so I can target the specific foreign key I want to update (solution at the end).
I wonder—isn't this a common use case in any app with relationships?
My question to the Payload team:
Is this not implemented in the Payload config because there's a better way to do it, or is it in the backlog? Maybe @jmikrut will know.
I'm asking because I'm trying to understand the correct approach. Based on my experience with other CMSs (like Directus), it's common to have
onUpdateandonDeleteproperties at the schema/collection level to handle this configuration.I'd love if Payload adds support for something like:
Utility workaround:
Note: This needs to be updated to support payload versioning
uncor3 commentedon Mar 10, 2025
Ty for your util workaround @Saissaken
Yes it is. I do not understand how it's not implemented in such a great cms, it's been 3 weeks since i submitted the issue and no maintainer has responded so far.
It may be because they support multiple DBs and they couldn't get it stable
I agree with this ^
SebastianSchuetze commentedon May 15, 2025
push+ just came accross this. If not implemented I would also be ok with a concept guideline on how to deal with it in best practices.
willemmulder commentedon May 19, 2025
Yes please! This is a common pattern that we'd ideally need some docs and/or functionality for.
engincannot commentedon May 21, 2025
@DanRibbens - I believe you were looking into this in #1209. Any idea if there are any plans to make this happen?
cdelacombaz commentedon Aug 20, 2025
+1
gwesterman commentedon Aug 21, 2025
+1
tonytkachenko commentedon Aug 21, 2025
+1
30 remaining items
joan-teriihoania commentedon Aug 4, 2026
We've tried tackling this as well and made a plugin package.
For now, we've tagged it as
EXPERIMENTALbut we've already made use of it and so far, we didn't get any problems. The approach is fundamentally the same as @mariovalney and his repository, with a bunch of utilities surrounding it. The plugin is broader and focuses on building a "graph" of all collection relationships, and the cascade deletion only makes use of the aggregated relationships.The flow is pretty simple:
uploadfields)beforeDeletehooks in order of "ascendance" to emulate the cascading effect by going through the relationship treeThe plugin also allows for unlinking which nulls the value instead of deleting the record (kind of like
ON DELETE SET NULLin SQL) or to a provided value.If anyone wants to give it a try and see if it works properly in their own set ups, that would be nice! I will be doing so on my side and once I feel like I have something stable, I'll remove the
EXPERIMENTALtag.I am open to feedback! I really wanted to contribute to PayloadCMS. It's been a while since I've enjoyed learning a new framework ^^ Please be gentle 🙏 Thank you!
EDIT: If need be, you can also reach out on the PayloadCMS's discord by pinging me @joprocorp
teamore commentedon Aug 26, 2026
I also stumbled over this issue today and it would be very useful if payload found a stable solution to this glitch. The current state forces developers to mess about manually with db migrations.
feat(lectures,albums): generalize parent-child cascade-delete + #292 …
MRNAQA commentedon Nov 18, 2026
same cause with a required
uploadinside an array, on 3.94.0 with postgres.banners[].imageis required, sostores_banners.image_idis NOT NULL, but the foreign key isON DELETE SET NULL. deleting the media fails withnull value in column "image_id" of relation "stores_banners" violates not-null constraint. the admin shows a server error and the media stays.repro: https://github.com/MRNAQA/payload-repros/tree/required-upload-array-delete
test(api): pin KI-9 and remeasure the seed button failures (#40) (#61)
brunoccalmeida commentedon Nov 28, 2026
This also affects the official
websitetemplate out of the box. The form builder plugin'sform-submissions.formfield is a required relationship, so once someone submits the template's contact form, that form can no longer be deleted:DELETE /api/forms/:id(and the admin's delete) returns 500, and the log hasnull value in column "form_id" of relation "form_submissions" violates not-null constraint. The admin only shows a generic error.Reproduced on a new app from
[email protected] -t website --db postgres(Postgres 18), with the seeded "Contact Form": one submission, thenDELETE /api/forms/:idreturns 500. The generated schema is"form_id" integer NOT NULLwithFOREIGN KEY ("form_id") REFERENCES "forms"("id") ON DELETE SET NULL. Deleting the submissions first, then the form, works.Untouched app (plus the generated migration): https://github.com/brunoccalmeida/payload-website-seed-race
docs: link the upstream reports for the seed button defects (#60) (#74)