首页 > 解决方案 > 如何使用 Sequelize ORM 强制复合外键存在?

问题描述

我不确定我的标题是否准确地反映了我想要做的事情,所以让我给出我的模型和关联

class MappingTable extends Model {
  static init(sequelize, DataTypes) {
    super.init({
      id: {
        autoIncrement: true,
        type: DataTypes.INTEGER,
        allowNull: false,
        primaryKey: true
      },
      a_id: {
        type: DataTypes.INTEGER,
        allowNull: false
      },
      a_type: {
        type: DataTypes.STRING(32),
        allowNull: false
      },
      e_id: {
        type: DataTypes.INTEGER,
        allowNull: false
      },
      e_type: {
        type: DataTypes.STRING(32),
        allowNull: true
      },
      include_children: {
        type: DataTypes.BOOLEAN,
        allowNull: true
      },
      c_id: {
        type: DataTypes.INTEGER,
        allowNull: false,
        references: {
          model: {
            tableName: 'c_table',
          },
          key: 'id'
        }
      },
    }, {
      sequelize,
      tableName: 'mapping',
      timestamps: false,
      indexes: [
        {
          name: 'assigned_mapping',
          unique: true,
          fields: [
            { name: 'id' },
          ]
        }
      ]
    });
    return MappingTable;
  }

在这个模型中,有 2 个复合键和 1 个外键:

(a_id, a_type) => 2 种类型对应 2 个表。

(b_id, b_type) => 2 种类型对应 2 个表。

(c_id) => 1 类型对应 1 个表。

我已经像这样建立了我的协会(我希望这足够清楚..)

MappingTable.belongsTo(c_type, { as: 'c_type', foreignKey: 'c_id'});
c_type.hasMany(MappingTable, { as: 'mapping', foreignKey: 'c_id'});

// A TYPE
MappingTable.belongsTo(a_type1, { ... where: { assignee_type: ATYPE.1}});
a_type1.hasMany(MappingTable, { ... where: { assignee_type: ATYPE.1}});
MappingTable.belongsTo(a_type2, { ... where: { assignee_type: ATYPE.2}});
a_type2.hasMany(MappingTable, { ... where: { assignee_type: ATYPE.2}});

// B TYPE
MappingTable.belongsTo(b_type1, { ... where: { assignee_type: BTYPE.1}});
b_type1.hasMany(MappingTable, { ... where: { assignee_type: BTYPE.1}});
MappingTable.belongsTo(b_type2, { ... where: { assignee_type: BTYPE.2}});
b_type2.hasMany(MappingTable, { ... where: { assignee_type: BTYPE.2}});

好的,现在我想创建一个新记录,如果我引用的所有外键 ID 对应于相应表中的有效记录。我可以想到两种方法来做到这一点:

要么有某种方法可以使用 Sequelize 强制执行此操作,要么我可以并行运行查询以确定是否所有记录都在尽可能短的时间内存在。有没有办法强制添加到使用复合键的模型中的外键是唯一的?

标签: javascriptdatabase-designsequelize.js

解决方案


推荐阅读