【发布时间】:2021-03-18 16:03:17
【问题描述】:
我目前在我的项目中有一个已经投入生产的数据库。但是我在之前的迁移中没有使用约束。现在我有表products、shops 和一个中间表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_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?
});
}
}
谢谢你:)
【问题讨论】:
标签: php laravel foreign-keys migration constraints