首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用后缀在N:M表中插入复合主键?

如何使用后缀在N:M表中插入复合主键?
EN

Stack Overflow用户
提问于 2021-12-01 02:50:51
回答 1查看 355关注 0票数 0

因此,我们有一个名为category_has_serviceprovider的表,它有一个复合主键(idCategory,idUser),还有一个表timeslots和一个主键(idTimeSlots).

我们要做的是:使用表category_has_serviceprovider时隙构建一个N:M表。结果应该是您可以在下一个图像中看到的表category_x_timeslots

如您所见,它有一个复合主键(idTimeSlots,idCategory,idUser),但是当我们在后缀中这样做时,我们得到了下一个映像:

因此,您可以看到category_has_serviceprovider.中缺少了idUser。我们能在后遗症中实现这一点吗?

category_x_timeslots表的代码是:

代码语言:javascript
复制
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;

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-12-04 20:03:22

我认为复合外键只支持在查询级别,而不是在数据库中创建的。作为数据库的另一种选择,我建议连接表有一个autoIncrement主键( id),并在外键列中添加索引,这些索引应该手动定义。

代码语言:javascript
复制
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;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70178569

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档