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:
- The adapter should assign the foreign key before creation if the included model is of a
belongsTo relation.
- Document this limitation clearly or provide a hook-based solution.
When using
sequelize, if abelongsToassociation field is defined withallowNull: 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
When trying to create a
Testinstance withownerincluded in theincludeoption, Sequelize throws a validation error sinceownerIdisnullat creation time.Expected Behavior
It should be possible to create a parent record along with its
belongsToassociation even ifallowNull: falseis 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:
belongsTorelation.