【问题标题】:How to add constraints to existing keys using laravel migration如何使用 laravel 迁移向现有键添加约束
【发布时间】:2021-03-18 16:03:17
【问题描述】:

我目前在我的项目中有一个已经投入生产的数据库。但是我在之前的迁移中没有使用约束。现在我有表productsshops 和一个中间表product_shop。问题是,如果我删除任何放在某个商店的产品,枢轴仍然保留在中间表中。我需要强制我的数据库的引用完整性,即使尚未更改/删除任何产品/商店。

我不想使用 Laravel 的事件监听器,因为当我删除一个对象而不先检索它时,它们不起作用。让我们考虑一下这个现有的结构,其中有我不想丢失的数据:

shops
  - id (int, auto-increment, index)
  - domain (string)

products
  - id (int, auto-increment, index)
  - name (string)
  - price (float)

product_shop
  - id (int, auto-increment, index)
  - product_id (int, foreign_key)
  - shop_id (int, foreign_key)

现在我想创建一个迁移,将约束设置为product_shop.product_idproduct_shop.shop_idonDelete: CASCADE, onUpdate: CASCADE。因此,无论我将在何处或以何种方式删除产品 - 如果我删除一个产品,所有相关的枢轴也将被删除。

但是我应该如何更改 migration->up()migration->down() 中的约束?

class EstablishConstraints extends Migration
{

  public function up()
  {
    Schema::table('product_shop', function (Blueprint $table) {
      $table->someMagic('product_id')->moreMagic('CASCADE');  // What here?
      $table->someMagic('shop_id')->moreMagic('CASCADE'); // ...and here?
    });
  }

  public function down()
  {
    Schema::table('product_shop', function (Blueprint $table) {
      $table->reverseMagic('product_id');  // How to reverse it?
      $table->reverseMagic('shop_id'); // ...on both columns?
    });

  }
}

谢谢你:)

【问题讨论】:

    标签: php laravel foreign-keys migration constraints


    【解决方案1】:

    找到解决方案:

    class EstablishConstraints extends Migration
    {
    
      public function up()
      {
        Schema::table('product_shop', function (Blueprint $table) {
          $table->foreignId('product_id')->change()
            ->constrained()
            ->cascadeOnDelete()
            ->cascadeOnUpdate();
    
          $table->foreignId('shop_id')->change()
            ->constrained()
            ->cascadeOnDelete()
            ->cascadeOnUpdate();
        });
      }
    
      public function down()
      {
        Schema::table('product_shop', function (Blueprint $table) {
          $table->dropForeign('product_shop_product_id_foreign');
          $table->dropForeign('product_shop_shop_id_foreign');
        });
    
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-04-01
      • 2017-07-18
      • 2019-03-24
      • 2017-03-27
      • 1970-01-01
      • 2021-08-30
      • 2012-03-06
      • 2020-09-21
      • 2020-03-12
      相关资源
      最近更新 更多