首页 > 解决方案 > 如何使用 laravel 迁移向现有键添加约束

问题描述

我目前在我的项目中有一个已经投入生产的数据库。但是我在之前的迁移中没有使用约束。现在我有表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_id为. 因此,无论我将在何处或如何删除产品 - 如果我删除一个产品,所有相关的枢轴也将被删除。product_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?
    });

  }
}

谢谢 :)

标签: phplaravelforeign-keysmigrationconstraints

解决方案


找到的解决方案:

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');
    });

  }
}

推荐阅读