Sequelize拥有并且属于许多人

时间:2017-06-03 22:24:27

标签: node.js database sequelize.js has-and-belongs-to-many polymorphic-associations

有没有办法与直通表进行多态自我关联(例如,集合有并且属于许多集合)?

尝试使http://docs.sequelizejs.com/manual/tutorial/associations.html#n-m适应这种情况:

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

collectionItem.js看起来像

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: {
    }
});

似乎Sequelize希望我通过另一个连接/通过表来区别对待这个名称,但这实际上是创建一个新表而不是获得真正的hasAndBelongsToMany类型关系。

  

错误:必须为多对多自我关联定义'as'

1 个答案:

答案 0 :(得分:1)

尝试明确并添加:

as: "CollectionItem"

as不创建新的连接表,只是给关系一个名称