laravel迁移添加外键的最佳方法

laravel迁移添加外键的最佳方法

问题描述:

一个简单的问题:我是Laravel的新手.我有此迁移文件:

Simple question: I'm new to Laravel. I have this migration file:

Schema::create('lists', function(Blueprint $table) {
    $table->increments('id'); 
    $table->string('title', 255);
    $table->integer('user_id')->unsigned(); 
    $table->foreign('user_id')->references('id')->on('users'); 
    $table->timestamps();
});

我想对其进行更新以添加onDelete('cascade').

I want to update it to add onDelete('cascade').

做到这一点的最佳方法是什么?

What's the best way to do this?

首先,您必须将user_id字段设为索引:

Firstly you have to make your user_id field an index:

$table->index('user_id');

之后,您可以创建一个具有级联操作的外键:

After that you can create a foreign key with an action on cascade:

$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

如果要通过新的迁移进行此操作,则必须首先删除索引和外键,然后从头开始做所有事情.

If you want to do that with a new migration, you have to remove the index and foreign key firstly and do everything from scratch.

在down()函数上,您必须先执行此操作,然后在up()函数上,执行我上面所写的内容:

On down() function you have to do this and then on up() do what I've wrote above:

$table->dropForeign('lists_user_id_foreign');
$table->dropIndex('lists_user_id_index');
$table->dropColumn('user_id');