联结 table 中的复合主键 - Sequelize

Composite primary key in junction table - Sequelize

使用 Sequelize 和 MySQL 数据库,我试图在联结 table 中实现复合主键组合,但不幸的是没有结果。

我有 tables:

它们是多对多的关系。在交界处 table user_has_project 我想要两个主键组合:user_id 和 project_id.

续集模型定义:

用户:

module.exports = function(sequelize, Sequelize) {

    var User = sequelize.define('user', {
        id: {
            autoIncrement: true,
            primaryKey: true,
            type: Sequelize.INTEGER(11)
        },

        name: {
            type: Sequelize.STRING(100),
            allowNull: false
        }
    },{
        timestamps: false,
        freezeTableName: true,
        underscored: true
});

User.associate = function (models) {
    models.user.belongsToMany(models.project, {
        through: 'user_has_project',
        foreignKey: 'user_id',
        primaryKey: true
    });
};

    return User;
}

项目:

module.exports = function(sequelize, Sequelize) {

    var Project = sequelize.define('project', {
        id: {
            autoIncrement: true,
            primaryKey: true,
            type: Sequelize.INTEGER(11)
        },

        name: {
            type: Sequelize.STRING(100),
            allowNull: false
        }
    },{
        timestamps: false,
        freezeTableName: true,
        underscored: true
    });


Project.associate = function (models) {
    models.project.belongsToMany(models.user, {
        through: 'user_has_project',
        foreignKey: 'project_id',
        primaryKey: true
    });
};

    return Project;
}

我试图在两个模型关联中使用 "primaryKey: true" 'force' user_has_project table 中的主键定义,但上面的定义仅创建 user_id作为 PRI 和 project_id 作为 MUL

什么是 Sequelize 版本?我在sqlite3中测试了Sequelize 4,上面的定义进行了查询

CREATE TABLE IF NOT EXISTS `user_has_project` (`created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL, `user_id` INTEGER(11) NOT NULL REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, `project_id` INTEGER(11) NOT NULL REFERENCES `project` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, PRIMARY KEY (`user_id`, `project_id`));

"PRIMARY KEY (user_id, project_id)"是你想要的吗?