联结表中的复合主键 - Sequelize

时间:2018-03-18 00:15:06

标签: mysql node.js model sequelize.js junction-table

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

我有桌子:

enter image description here

他们与许多人有很多关系。在联结表user_has_project中,我想要两个主键组合:user_id和project_id。

Sequelize模型定义:

用户:

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;
}

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

1 个答案:

答案 0 :(得分:1)

什么是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_idproject_id)”是您想要的吗?