sequelize icon indicating copy to clipboard operation
sequelize copied to clipboard

ON DELETE constraint should default to CASCADE if foreignKey has allowNull: false

Open mickhansen opened this issue 11 years ago • 5 comments

var Foo = this.sequelize.define('Foo', { 
  bar_id: { type: Sequelize.INTEGER, allowNull: false }
});
var Bar = this.sequelize.define('Bar', {});

Foo.belongsTo(Bar, { foreignKey: 'bar_id'});

return Bar.sync({force: true}).then(function () {
  return Foo.sync({force: true});
});

Will fail on MySQL (haven't tested others so far) because the cascade defaults to SET NULL which "obviously" (took me a while to figure it out) obviously doesn't work well with a field that can't be NULL'ed.

Sequelize should check the foreignkey attribute definition, and if allowNull is false it should perhaps either use CASCADE by default or turn off constraints.

mickhansen avatar Jan 04 '15 18:01 mickhansen

A big +1 to this. This also took me a half day to figure out.

I might also be nice to have more options available to sync so that clients can turn the CASCADE and/or constraints off even when allowNull is set to true.

EToreo avatar Mar 10 '15 19:03 EToreo

+1.

mvallerie avatar May 01 '15 19:05 mvallerie

I'm using Sequelize 3.13 with PostgreSQL 9.4

var Foo = sequelize.define('Foo', {});
var Bar = sequelize.define('Bar', {});
Bar.belongsTo(Foo, {
    foreignKey: { allowNull: false },
});

but FooId doesn't have ON DELETE CASCADE.

phuvo avatar Nov 07 '15 07:11 phuvo

mine is not working yet...

igordeoliveirasa avatar Jul 24 '17 17:07 igordeoliveirasa

@phuvo It's because you use belongsTo instead of hasOne/hasMany. They seem to have different behaviors with the ON DELETE constraint. See the description of this PR: https://github.com/sequelize/sequelize/pull/4506

Mageek627 avatar Aug 06 '20 00:08 Mageek627