Skip to content

Docs: Polymorphic associations use v6 constraints option instead of v7 foreignKeyConstraints #820

@klondikemarlen

Description

@klondikemarlen

Issue Description

What was unclear/insufficient/not covered in the documentation

The polymorphic associations documentation at https://sequelize.org/docs/v7/associations/polymorphic-associations/ uses the Sequelize v6 option name constraints: false, but in Sequelize v7 this option was renamed to foreignKeyConstraints: false.

The current example shows:

@HasMany(() => Comment, {
  inverse: { 
    as: 'videos'
  },
  foreignKey: 'targetId',
  constraints: false,
  scope: { 
    targetModel: 'video'
  }
})

When users copy this pattern for v7, they get:

SequelizeAssociationError: Defining HasOne association "..." from X to Y failed

The correct v7 syntax should use foreignKeyConstraints: false.

Additionally:

  • No HasOne example exists for polymorphic associations, only HasMany
  • The HasOne documentation page doesn't mention foreignKeyConstraints at all

If possible: Provide some suggestion on how we can enhance the docs

  1. Update the example to use the v7 option name:

    @HasMany(() => Comment, {
      inverse: { 
        as: 'videos'
      },
      foreignKey: 'targetId',
      foreignKeyConstraints: false,
      scope: { 
        targetModel: 'video'
      }
    })
  2. Add a HasOne example for single-record polymorphic relationships (e.g., one attachment per record):

    @HasOne(() => Attachment, {
      foreignKey: 'targetId',
      foreignKeyConstraints: false,
      inverse: { 
        as: 'video'
      },
      scope: { 
        targetType: 'Video'
      },
    })
    declare attachment?: NonAttribute<Attachment>
  3. Document foreignKeyConstraints on the HasOne associations page.

Additional context

From the v7 source code https://github.com/sequelize/sequelize/blob/c7f6a867b99d7c085e9fa488e91d233dba32ff7b/packages/core/src/associations/base.ts#L319:

export interface AssociationOptions<ForeignKey extends string = string> {
  /**
   * Should ON UPDATE, ON DELETE, and REFERENCES constraints be enabled on the foreign key.
   */
  foreignKeyConstraints?: boolean;
  // ...
}

Discovered while using Sequelize 7.0.0-alpha.46 with decorator-based polymorphic HasOne associations.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions