首页 文章

联结表中的复合主键 - Sequelize

提问于
浏览
0

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

我有 table :

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

我试图在两个模型关联中使用“primaryKey:true”在user_has_project表中“强制”主键定义,但上面的定义只创建了user_id作为PRI而project_id作为MUL

1 回答

  • 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 )”你想要什么?

相关问题