我们如何使用 sequelize 在 N:M table 中插入复合主键?

How can we insert a composite primary key in N:M table using sequelize?

所以,我们有一个名为 category_has_serviceprovider 的 table,它有一个复合主键 (idCategory, idUser) 我们有一个 table timeslots 主键 (idTimeSlots).

我们想要做的是:我们想要使用 table category_has_serviceprovider 时隙 。结果应该是您可以在下一张图片中看到的 table category_x_timeslots

如您所见,它有一个复合主键 (idTimeSlots, idCategory, idUser),但是当我们在 sequelize 中这样做时,我们会得到下一张图片:

因此,您可以看到它缺少 category_has_serviceprovider 中的 idUser。我们可以在 sequelize 中实现吗?

category_x_timeslots table 的代码是:

const Category_has_ServiceProvider = require("../../category_has_serviceProvider/api/category_has_serviceProvider");
const TimeSlots = require("../../timeslots/api/timeslots");

const category_x_TimeSlots = dbconfig.sequelize.define('Category_x_TimeSlots', {
    occupied : {
        type: dbconfig.Sequelize.BOOLEAN,
        allowNull: false
    },
    experience : {
        type: dbconfig.Sequelize.INTEGER,
        allowNull: false
    }
}, {
    freezeTableName: true,
    timestamps: false
});

Category_has_ServiceProvider.belongsToMany(TimeSlots, {foreignKey: 'idCategory', through: category_x_TimeSlots});
TimeSlots.belongsToMany(Category_has_ServiceProvider, {foreignKey: 'idTimeSlots',through: category_x_TimeSlots});


category_x_TimeSlots.sync()

module.exports = category_x_TimeSlots;

如果您需要查看其他 2 个 table 的实现,请告诉我。

我认为复合外键仅在查询级别受支持,它们不是在数据库中创建的。作为数据库的替代方案,我建议联结 table 有一个自动增量主键(id)并在应该手动定义的外键列上添加索引。

const Category_has_ServiceProvider = require("../../category_has_serviceProvider/api/category_has_serviceProvider");
const TimeSlots = require("../../timeslots/api/timeslots");

const category_x_TimeSlots = dbconfig.sequelize.define('Category_x_TimeSlots', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
      allowNull: false
    },
    occupied: {
        type: dbconfig.Sequelize.BOOLEAN,
        allowNull: false
    },
    experience: {
        type: dbconfig.Sequelize.INTEGER,
        allowNull: false
    },
    idCategory: {
      type: DataTypes.INTEGER,
      allowNull: false
    },
    idUser: {
      type: DataTypes.INTEGER,
      allowNull: false
    },
    idTimeSlots: {
      type: DataTypes.INTEGER,
      allowNull: false
    },
}, {
    freezeTableName: true,
    timestamps: false,
    indexes: [{
        unique: true,
        fields: ['idCategory', 'idUser', 'idTimeSlots']
    }]
});

Category_has_ServiceProvider.belongsToMany(TimeSlots, {foreignKey: ['idCategory', 'idUser'], through: category_x_TimeSlots});
TimeSlots.belongsToMany(Category_has_ServiceProvider, {foreignKey: 'idTimeSlots',through: category_x_TimeSlots});


category_x_TimeSlots.sync()

module.exports = category_x_TimeSlots;