简体   繁体   中英

How to add Foreign Key and Cascade properties with Sequelize?

I want to implement this MySQL query with Sequelize for my express.js Model.

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. 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. 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'
      }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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