Skip to content

sequelize: belongsTo relation with allowNull: false causes creation failure due to late association assignment #2

@xziy

Description

@xziy

When using sequelize, if a belongsTo association field is defined with allowNull: false, the creation of a model instance fails. This happens because the foreign key is not yet assigned when the record is first inserted, as the adapter binds associations after the record is created.

Reproduction

@ForeignKey(() => UserAP)
@Column({ type: DataType.INTEGER, allowNull: false }) // <-- this
declare ownerId: number;

@BelongsTo(() => UserAP, { as: 'owner' })
declare owner?: UserAP;

When trying to create a Test instance with owner included in the include option, Sequelize throws a validation error since ownerId is null at creation time.

Expected Behavior

It should be possible to create a parent record along with its belongsTo association even if allowNull: false is set on the foreign key column.

Workaround

The only workaround currently is to set allowNull: true, which weakens data integrity enforcement at the database level.

Suggested Fix

Either:

  1. The adapter should assign the foreign key before creation if the included model is of a belongsTo relation.
  2. Document this limitation clearly or provide a hook-based solution.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions