0

Is there a way to do a polymorphic self-association with a through table (e.g. Collection has and belongs to many Collections)?

Trying to adapt http://docs.sequelizejs.com/manual/tutorial/associations.html#n-m to this scenario:

// Inside collection.js associate
Collection.belongsToMany(Collection, {
    through: {
        model: models.CollectionItem,
        unique: false,
        scope: {
            collectible: 'collection'
        }
    },
    foreignKey: 'collectibleUid',
    constraints: false
});

Where collectionItem.js would look like

const CollectionItem = sequelize.define("CollectionItem", {
    uid: {
        type: DataTypes.BIGINT,
        primaryKey: true
    },
    collectionUid: {
        type: DataTypes.BIGINT,
        allowNull: false,
        unique: 'collection_item_collectible'
    },
    order: {
        type: DataTypes.INTEGER,
        allowNull: false,
        defaultValue: 0
    },
    collectibleUid: {
        type: DataTypes.BIGINT,
        allowNull: false,
        references: null, // Because the column is polymorphic, we cannot say that it REFERENCES a specific table
        unique: 'collection_item_collectible'
    },
    collectible: {
        type: DataTypes.STRING,
        allowNull: false,
        unique: 'collection_item_collectible'
    }
}, {
    classMethods: {
    }
});

It seems Sequelize wants me to name this differently through yet another join / through table, but that would essentially be creating a new table versus just getting a true hasAndBelongsToMany type relationship.

Error: 'as' must be defined for many-to-many self-associations

iwasrobbed
  • 46,496
  • 21
  • 150
  • 195

1 Answers1

1

Try being explicit and add:

as: "CollectionItem"

as does not create a new join table, it just gives the relation a name

iwasrobbed
  • 46,496
  • 21
  • 150
  • 195
Nicolas Gramlich
  • 2,790
  • 19
  • 19