website icon indicating copy to clipboard operation
website copied to clipboard

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

Open klondikemarlen opened this issue 2 months ago • 0 comments

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.

klondikemarlen avatar Jan 07 '26 18:01 klondikemarlen