【问题标题】:Sequelize belongToMany cascade deleteSequelize belongsToMany 级联删除
【发布时间】:2021-03-16 02:29:32
【问题描述】:

大家好。我有两个表(项目,配置)连接为 belongsToMany(项目配置)。我需要删除项目(Project),因此我需要删除与该项目相关的配置。我该怎么做?

【问题讨论】:

    标签: node.js sequelize.js sequelize-cli


    【解决方案1】:

    您需要在 'projects.model.js' 中使用 onDelete: 'CASCADE':

    const Projects = sequelize.define('projects', other_stuffs);
    ...
    Projects.associate = function (models) {
      this.belongsToMany(models.get('configurations'), {
        through: 'project_configurations',
        foreignKey: 'project_id',
        onUpdate: 'CASCADE', // optional
        onDelete: 'CASCADE',
      });
      return this;
    };
    ...
    

    'configurations.model.js'

    const Configurations = sequelize.define('configurations', other_stuffs);
    ...
    Configurations.associate = function (models) {
      this.belongsToMany(models.get('projects'), {
        through: 'project_configurations',
        foreignKey: 'configurations_id',
        onUpdate: 'CASCADE', // optional
        onDelete: 'CASCADE',
      });
      return this;
    };
    ...
    

    【讨论】:

      猜你喜欢
      • 2017-06-10
      • 1970-01-01
      • 2017-08-15
      • 2015-01-14
      • 2018-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多