gpt4 book ai didi

php - 如何修改外键约束以删除级联

转载 作者:行者123 更新时间:2023-11-29 07:32:18 29 4
gpt4 key购买 nike

基本上,我已经为我的表创建了此迁移

 // ...
$table->integer('project_id')->unsigned();
$table->primary('project_id');
$table->foreign('project_id')->references('id')->on('project');
// ...

但我忘记包含onDelete('cascade')。我如何更新此迁移以添加它?

最佳答案

迁移应该描述对数据库的增量更改,以便可以对数据库模式进行版本控制。 不应更改过去的迁移,但如果需要任何更改,则应创建一个新的迁移文件来应用必要的更改。

在您的情况下,您需要一个新的迁移文件,该文件将删除旧的约束定义并应用新的约束定义。下面的方法就可以解决这个问题:

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddOnCascadeToProjectId extends Migration
{
public function up()
{
Schema::table('your_table', function (Blueprint $table) {
//drop the old constraint
$table->dropForeign('your_table_project_id_foreign');
//create new constraint with ON CASCADE
$table->foreign('project_id')->references('id')->on('project')->onDelete('cascade');
});
}

public function down()
{
Schema::table('your_table', function (Blueprint $table) {
//drop new constraint with ON CASCADE
$table->dropForeign('your_table_project_id_foreign');
//recreate the old constraint
$table->foreign('project_id')->references('id')->on('project');
});
}
}

关于php - 如何修改外键约束以删除级联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32173368/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com