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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26437342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:47:23  来源:igfitidea点击:

laravel migration best way to add foreign key

laravelforeign-keysmigration

提问by reshma kr

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

简单的问题:我是 Laravel 的新手。我有这个迁移文件:

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();
});

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

我想更新它以添加onDelete('cascade').

What's the best way to do this?

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

回答by Nerijus Masikonis

Firstly you have to make your user_idfield an index:

首先,您必须使您的user_id字段成为索引:

$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.

如果你想通过新的迁移来做到这一点,你必须首先删除索引和外键,然后从头开始做所有事情。

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

在 down() 函数上你必须这样做,然后在 up() 上做我上面写的:

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

回答by Raman Deep Bajwa

Schema::create('roles',function(Blueprint $table){

    $table->bigIncrements('id');
    $table->string('name');
    $table->timestamps();

});

Schema::create('permissions',function(Blueprint $table){

    $table->unsignedBigInteger('role_id');
    $table->foreign('role_id')->references('id')->on('roles');
    $table->string('permission');

});

回答by Rohan

$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');

In this example, we are stating that the user_idcolumn references the idcolumn on the userstable. Make sure to create the foreign key column first! The user_idcolumn is declared unsigned because it cannot have negative value.

在这个例子中,我们声明user_id列引用了users表上的id列。确保先创建外键列!该USER_ID列声明无符号,因为它不能有负值。

You may also specify options for the "on delete" and "on update" actions of the constraint:

您还可以为约束的“删除时”和“更新时”操作指定选项:

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

To drop a foreign key, you may use the dropForeignmethod. A similar naming convention is used for foreign keys as is used for other indexes:

要删除外键,您可以使用dropForeign方法。外键使用与其他索引类似的命名约定:

$table->dropForeign('posts_user_id_foreign');

If you are fairly new to Laraveland Eloquent, try out the Laravel From Scratchseries available on laracasts. It is a great guide for beginners.

如果你是相当新的Laravel口才,尝试了Laravel的划痕上laracasts提供系列。对于初学者来说,这是一个很好的指南。

回答by geoandri

You should create a new migration file let's say 'add_user_foreign_key.php'

您应该创建一个新的迁移文件,比如“add_user_foreign_key.php”

public function up()
{
    Schema::table('lists', function(Blueprint $table)
    {
         $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('lists', function(Blueprint $table)
    {
    $table->dropForeign('user_id'); //
    });
}  

The run

运行

 php artisan migrate

回答by PW_Parsons

In Laravel 7 it can be done in one line

在 Laravel 7 中,它可以在一行中完成

$table->foreignId('user_id')->constrained()->cascadeOnDelete();

$table->foreignId('user_id')->constrained()->cascadeOnDelete();

回答by Tomas Buteler

If you want to add onDelete('cascade'), just drop the indexes and create them again:

如果要添加onDelete('cascade'),只需删除索引并再次创建它们:

public function up()
{
    Schema::table('lists', function($table)
    {
        $table->dropForeign('lists_user_id_foreign');

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

public function down()
{
    Schema::table('lists', function($table)
    {
        $table->dropForeign('lists_user_id_foreign');

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

回答by Jayani Nadeesha

Schema::table('posts', function (Blueprint $table) {
    $table->unsignedInteger('user_id');

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

回答by samad.naghipour

I was doing the same but got error " id not exist" => so I changed my migration file as below :

我也在做同样的事情,但得到了错误“id不存在”=>所以我改变了我的迁移文件如下:

question table migration content:

题表迁移内容:

$table->id() => should change to $table->increments('id')

$table->id() => 应该改为 $table->increments('id')

definitions of foreign key in Reply table:

回复表中外键的定义:

$table->foreign('question_id')->references('id')->on('questions')->onDelete('cascade');

$table->foreign('question_id')->references('id')->on('questions')->onDelete('cascade');

now your foreign key will work.

现在您的外键将起作用。