php - 如何使用 laravel 迁移向现有键添加约束
问题描述
我目前在我的项目中有一个已经投入生产的数据库。但是我在之前的迁移中没有使用约束。现在我有表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?
});
}
}
谢谢 :)
解决方案
找到的解决方案:
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');
});
}
}
推荐阅读
- batch-file - 如何使用 RoboCopy 处理网络错误
- c# - 删除变音符号,某些字母上的某些变音符号除外
- python - 多处理 python 的行为不符合预期
- html - HTML+CSS:自动换行后 TD 之间不需要的空间
- sql - phpmyadmin:将数据输入主键时未填充外键
- git - Git 和 Svn - dcommit 损坏了我的代码
- python - 如何使用循环语句一一读取DataFrame中的数据?
- angular - Angular Elements:@Input 装饰器不适用于变量
- javascript - JS 计算器不能在 wordpress 中工作,脚本在旧网站上工作
- python - 全局变量不跨 FUNCTIONS