Skip to content

foreign keys with cascade delete #11177

Open

Description

@uncor3

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

https://github.com/uncor3/payload-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

  1. added
    status: needs-triage
    validate-reproduction
    on Feb 14, 2025
  2. removed
    validate-reproduction
    on Feb 14, 2025
  3. Saissaken commented on Mar 5, 2025

    @Saissaken

    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 onUpdate and onDelete properties at the schema/collection level to handle this configuration.

    I'd love if Payload adds support for something like:

    {
        name: "createdBy",
        type: "relationship",
        relationTo: "users",
        hasMany: false,
        required: true,
        onDelete: "cascade"
    },

    Utility workaround:

    export function updateFk(
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      schema: any,
      tableName: string,
      tableColumnName: string,
      foreignTableName: string,
      foreignColumnName: string,
      onUpdate: string,
      onDelete: string,
    ) {
      const indexInlineFKs = Symbol.for(`drizzle:PgInlineForeignKeys`);
      const indexTableName = Symbol.for(`drizzle:Name`);
    
      const fkeys =
        schema.relations[`relations_${tableName}`].table[indexInlineFKs];
    
      // @ts-expect-error workaround
      fkeys.forEach((foreignKey) => {
        const ref = foreignKey.reference();
    
        if (ref.columns.length !== 1) {
          throw new Error("Only one column is supported");
        }
    
        if (ref.foreignColumns.length !== 1) {
          throw new Error("Only one foreign column is supported");
        }
    
        const actualColumnName = ref.columns[0].name;
        const actualForeignTableName = ref.foreignTable[indexTableName];
        const actualForeignColumnName = ref.foreignColumns[0].name;
    
        if (actualColumnName !== tableColumnName) return;
        if (actualForeignTableName !== foreignTableName) return;
        if (actualForeignColumnName !== foreignColumnName) return;
    
        foreignKey.onUpdate = onUpdate;
        foreignKey.onDelete = onDelete;
      });
    }

    Note: This needs to be updated to support payload versioning

  4. uncor3 commented on Mar 10, 2025

    @uncor3
    Author

    Ty for your util workaround @Saissaken

    I wonder—isn't this a common use case in any app with relationships?

    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'd love if Payload adds support for something like:

    {
        name: "createdBy",
        type: "relationship",
        relationTo: "users",
        hasMany: false,
        required: true,
        onDelete: "cascade"
    } 

    I agree with this ^

  5. SebastianSchuetze commented on May 15, 2025

    @SebastianSchuetze

    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.

  6. willemmulder commented on May 19, 2025

    @willemmulder

    Yes please! This is a common pattern that we'd ideally need some docs and/or functionality for.

  7. engincannot commented on May 21, 2025

    @engincannot

    @DanRibbens - I believe you were looking into this in #1209. Any idea if there are any plans to make this happen?

  8. cdelacombaz commented on Aug 20, 2025

    @cdelacombaz
    Contributor

    +1

  9. gwesterman commented on Aug 21, 2025

    @gwesterman
    Contributor

    +1

  10. tonytkachenko commented on Aug 21, 2025

    @tonytkachenko
    Contributor

    +1

  11. 30 remaining items

  12. joan-teriihoania commented on Aug 4, 2026

    @joan-teriihoania

    We've tried tackling this as well and made a plugin package.

    For now, we've tagged it as EXPERIMENTAL but 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:

    1. At startup, scan through the collection for relationship fields (including upload fields)
    2. Then, add beforeDelete hooks in order of "ascendance" to emulate the cascading effect by going through the relationship tree

    The plugin also allows for unlinking which nulls the value instead of deleting the record (kind of like ON DELETE SET NULL in 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 EXPERIMENTAL tag.

    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

  13. teamore commented on Aug 26, 2026

    @teamore

    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.

  14. removed
    status: needs-triage
    on Oct 1, 2026
  15. MRNAQA commented on Nov 18, 2026

    @MRNAQA

    same cause with a required upload inside an array, on 3.94.0 with postgres. banners[].image is required, so stores_banners.image_id is NOT NULL, but the foreign key is ON DELETE SET NULL. deleting the media fails with null 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

  16. brunoccalmeida commented on Nov 28, 2026

    @brunoccalmeida

    This also affects the official website template out of the box. The form builder plugin's form-submissions.form field 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 has null 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, then DELETE /api/forms/:id returns 500. The generated schema is "form_id" integer NOT NULL with FOREIGN 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions