简体   繁体   English

如何使用 Sequelize 添加外键和级联属性?

[英]How to add Foreign Key and Cascade properties with Sequelize?

I want to implement this MySQL query with Sequelize for my express.js Model.我想用 Sequelize 为我的 express.js Model 实现这个 MySQL 查询。

CREATE TABLE `Serivce_Area` (
  `service_area_id` int auto_increment primary key,
  `service_id` int not null,
  `area_id` int not null,  
  FOREIGN KEY (service_id) REFERENCES Service_Credential(service_id) ON UPDATE CASCADE ON DELETE CASCADE,
  FOREIGN KEY (area_id) REFERENCES Area_Details(area_id) ON UPDATE CASCADE ON DELETE CASCADE
);

Here I have two other tables named Service_Credential and Area_Details with two primary keys naming service_id and area_id.在这里,我还有另外两个名为 Service_Credential 和 Area_Details 的表,其中两个主键分别命名为 service_id 和 area_id。 This is how far I've done.这就是我所做的。

const serviceArea = sequelize.define('Serivce_Area', {
    service_area_id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        allowNull: false,
        primaryKey: true
    },
    service_id:{
        type: Sequelize.INTEGER,
        allowNull: false
    },
    area_id: {
        type: Sequelize.INTEGER,
        allowNull: false
    },
});

But I'm having trouble with adding the Foreign Key and Cascade properties.但是我在添加外键和级联属性时遇到了麻烦。 I have checked the documentation.我已经检查了文档。 But still I'm not sure how to do it.但我仍然不知道该怎么做。 Besides, some stackoverflow answers contains belongsTo and hasMany properties which I'm not sure how to use in this situation.此外,一些stackoverflow答案包含belongsTohasMany属性,我不确定如何在这种情况下使用。 Please help me with this.请帮我解决一下这个。

My friend helped me with this solution.我的朋友帮我解决了这个问题。 And it worked.它奏效了。

    service_area_id: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    service_id: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      references: {
        model: 'Service_Credential',
        key: 'service_id'
      }
    },
    area_id: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      references: {
        model: 'Area_Details',
        key: 'area_id'
      }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM