【问题标题】:Composite primary key in junction table - Sequelize联结表中的复合主键 - Sequelize
【发布时间】:2018-08-26 20:23:13
【问题描述】:

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

我有桌子:

它们是多对多的关系。在联结表 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

【问题讨论】:

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


    【解决方案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_id, project_id)”是你想要的吗?

    【讨论】:

    • 我正在使用 Sequelize 4.33.4。我已经对其进行了测试,并且以前也可以使用,问题出在我在表格摘要中使用“Sequel Pro”的应用程序显示为MUL,但实际上它们都是PRI。我去 phpMyAdmin 检查并有正确的。不管怎样,谢谢你的回答。
    猜你喜欢
    • 2020-03-28
    • 1970-01-01
    • 1970-01-01
    • 2021-02-01
    • 2016-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多