问题描述
我的项目中目前有一个已投入生产的数据库。但是我在之前的迁移中没有使用约束。现在我有表 products
、shops
和中间表 product_shop
。问题是,如果我删除任何已经放在某个商店的产品,枢轴仍然保留在中间表中。我需要强制我的数据库的参照完整性,即使尚未更改/删除任何产品/商店。
我不想使用 Laravel 的事件侦听器,因为当我删除一个对象而不先检索它时,它们不起作用。让我们考虑一下现有的结构,其中有我不想丢失的数据:
shops
- id (int,auto-increment,index)
- domain (string)
products
- id (int,index)
- name (string)
- price (float)
product_shop
- id (int,index)
- product_id (int,foreign_key)
- shop_id (int,foreign_key)
现在我想创建一个迁移,在其中使用 product_shop.product_id
将约束设置为 product_shop.shop_id
和 onDelete: 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?
});
}
}
谢谢:)
解决方法
找到解决方案:
Action ac= new Action(driver);
Ac.moveToElement(dropdown).moveToElement(User).click().build().perform();