laravel迁移添加外键的最佳方法 [英] laravel migration best way to add foreign key

查看:506
本文介绍了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');

这篇关于laravel迁移添加外键的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆