Skip to content

Foreign Key Constraint Violation with Blocks Used Across Multiple Collections #14350

@technicaldirector

Description

@technicaldirector

Describe the Bug

When using the same block (with a custom dbName) across multiple collections that have versioning enabled, PayloadCMS creates a foreign key constraint that only references one parent table, causing database errors when trying to save documents in other collections.

2025-10-25.18-20-27.mp4

Link to the code that reproduces this issue

https://github.com/technicaldirector/payload-block-issue

Reproduction Steps

  1. Create a block with a custom dbName property:
export const RelatedProjectsBlock: Block = {
  slug: 'relatedProjectsBlock',
  dbName: 'relProjBlk',  // Custom short name
  interfaceName: 'RelatedProjects',
  fields: [/* ... */]
}
  1. Use this block in multiple collections with versioning enabled:
// Pages Collection
export const Pages: CollectionConfig = {
  slug: 'pages',
  versions: {
    drafts: { autosave: { interval: 100 } },
    maxPerDoc: 50,
  },
  fields: [
    {
      name: 'layout',
      type: 'blocks',
      blocks: [RelatedProjectsBlock, /* other blocks */]  // Using blocks, not blockReferences
    }
  ]
}

// Projects Collection
export const Projects: CollectionConfig = {
  slug: 'projects',
  versions: {
    drafts: { autosave: { interval: 100 } },
    maxPerDoc: 50,
  },
  fields: [
    {
      name: 'layout',
      type: 'blocks',
      blocks: [RelatedProjectsBlock, /* other blocks */]  // Using blocks, not blockReferences
    }
  ]
}
  1. Create or edit a document in the Projects collection
  2. Add a RelatedProjectsBlock to the layout
  3. Try to save the document (autosave or manual save)

Expected Behavior

The document should save successfully, and the version table should correctly reference the parent document in the _projects_v table.

Actual Behavior

The save operation fails with a foreign key constraint violation:

ERROR: There was an error while saving a version for the Project with ID 1.
DatabaseError: insert or update on table "_relProjBlk_v" violates foreign key constraint "_relProjBlk_v_parent_id_fk"

Detail: Key (_parent_id)=(38) is not present in table "_pages_v".

The error indicates that the foreign key constraint _relProjBlk_v_parent_id_fk is pointing to the _pages_v table instead of the _projects_v table.

Which area(s) are affected? (Select all that apply)

db: postgres, area: core

Environment Info

- Payload Version: 3.61.1
- Next.js Version: 15.3.0
- Node Version: node:22.14.0-alpine

Metadata

Metadata

Assignees

No one assigned

    Labels

    status: needs-triagePossible bug which hasn't been reproduced yet

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions