Manytomany self-referencial relationship breaks

Here subParameterOutlines is separate table that maps a parameterOutline to multiple other parameterOutlines as sub-parameters if that makes sense.

Expected behavior

It should not throw error when trying to start the server.

Actual behavior

It throws following error when trying to start the server:

/Users/bk/server admin/node_modules/sequelize/lib/associations/belongs-to-many.js:81
throw new AssociationError(’‘as’ must be defined for many-to-many self-associations’);
^

SequelizeAssociationError: ‘as’ must be defined for many-to-many self-associations
at new BelongsToMany (/Users/bk/server admin/node_modules/sequelize/lib/associations/belongs-to-many.js:81:13)
at Function.belongsToMany (/Users/bk/server admin/node_modules/sequelize/lib/associations/mixin.js:64:25)
at Function.ParameterOutlines.associate (/Users/bk/server admin/models/parameter-outlines.js:49:23)
at /Users/bk/server admin/models/index.js:39:19

Failure Logs

/Users/bk/server admin/node_modules/sequelize/lib/associations/belongs-to-many.js:81
throw new AssociationError(’‘as’ must be defined for many-to-many self-associations’);
^

SequelizeAssociationError: ‘as’ must be defined for many-to-many self-associations
at new BelongsToMany (/Users/bk/server admin/node_modules/sequelize/lib/associations/belongs-to-many.js:81:13)
at Function.belongsToMany (/Users/bk/server admin/node_modules/sequelize/lib/associations/mixin.js:64:25)
at Function.ParameterOutlines.associate (/Users/bk/server admin/models/parameter-outlines.js:49:23)
at /Users/bk/server admin/models/index.js:39:19

Context

Please provide any relevant information about your setup.

"chalk": "~1.1.3",
"cookie-parser": "1.4.4",
"cors": "2.8.5",
"debug": "~4.0.1",
"dotenv": "~6.1.0",
"express": "~4.16.3",
"express-jwt": "5.3.1",
"forest-express-sequelize": "^6.0.0",
"morgan": "1.9.1",
"require-all": "^3.0.0",
"sequelize": "~5.15.1",
"pg": "~8.2.2"
1 Like

Hi @BK42,

Thank you for sharing your issue!

As stated by the error message, it seems that sequelize requires an as option when defining a belongsToMany relationship.

If you look at your parent foreignKey definition, it has an as option that allows it to be called with another name. You must define the same on your belongsToMany definitions:

ParameterOutlines.belongsToMany(models.parameterOutlines, {
  through: 'subParameterOutlines',
  foreignKey: 'parameter_outline_id',
  otherKey: 'sub_parameter_outline_id',
  as: 'subParameterOutlines', // this is an example name, use one that suits your needs
});

I hope this helps!

2 Likes