Skip to content

Relation constraints not being applied correctly #5865

@tjenkinson

Description

@tjenkinson

What you are doing?

I have a couple of models and the belongsToMany relation for each of them, and am trying to set the onDelete rule so one is 'cascade' and the other is 'restrict'. Using postgres.

User.belongsToMany(Group, {through: 'userToGroup', onDelete: 'CASCADE'});
// do not allow a group to be deleted if it has references to users
Group.belongsToMany(User, {through: 'userToGroup', onDelete: 'RESTRICT'});

Then I do sequelize.sync().

What do you expect to happen?

In posrgres the constraints should be:

  CONSTRAINT "userToGroup_groupId_fkey" FOREIGN KEY ("groupId")
      REFERENCES tom_web_portal_dev.groups (id) MATCH SIMPLE
      ON UPDATE CASCADE ON DELETE RESTRICT,
  CONSTRAINT "userToGroup_userId_fkey" FOREIGN KEY ("userId")
      REFERENCES tom_web_portal_dev.users (id) MATCH SIMPLE
      ON UPDATE CASCADE ON DELETE CASCADE

What is actually happening?

In postgres the constraints are both 'restrict':

  CONSTRAINT "userToGroup_groupId_fkey" FOREIGN KEY ("groupId")
      REFERENCES tom_web_portal_dev.groups (id) MATCH SIMPLE
      ON UPDATE CASCADE ON DELETE RESTRICT,
  CONSTRAINT "userToGroup_userId_fkey" FOREIGN KEY ("userId")
      REFERENCES tom_web_portal_dev.users (id) MATCH SIMPLE
      ON UPDATE CASCADE ON DELETE RESTRICT

If I switch the order:

// do not allow a group to be deleted if it has references to users
Group.belongsToMany(User, {through: 'userToGroup', onDelete: 'RESTRICT'});
User.belongsToMany(Group, {through: 'userToGroup', onDelete: 'CASCADE'});

then it results in:

  CONSTRAINT "userToGroup_groupId_fkey" FOREIGN KEY ("groupId")
      REFERENCES tom_web_portal_dev.groups (id) MATCH SIMPLE
      ON UPDATE CASCADE ON DELETE CASCADE,
  CONSTRAINT "userToGroup_userId_fkey" FOREIGN KEY ("userId")
      REFERENCES tom_web_portal_dev.users (id) MATCH SIMPLE
      ON UPDATE CASCADE ON DELETE CASCADE

so it look like the latest value takes precedence.

Dialect: postgres
Database version: 9.1.20
Sequelize version: 3.23.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    type: bugDEPRECATED: replace with the "bug" issue type

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions