简体   繁体   中英

Sequelize has and belongs to many

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

Trying to adapt http://docs.sequelizejs.com/manual/tutorial/associations.html#nm 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

Try being explicit and add:

as: "CollectionItem"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM