Laravel::Migration - 如何通过 Laravel 迁移创建外键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48180314/
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-14 17:13:35  来源:igfitidea点击:

Laravel::Migration - how to create foreign key by laravel migration?

laravellaravel-5.5

提问by wr-98

How can make a referenced keyand foreign keyin laravelby migrations. Think I have to migrations file in database directory in laravel which both of theme create a different table in my database. the first migration crate a table that is for posts which has a column in the name of Id. the second migration create comments table that has a column in the name of post_id. Now the Id column in posts table is referenced keyand the post_id in comments table is foreign key, how can I connect these two columns together?

怎样才能使 areferenced keyforeign keyin laravelby migrations. 认为我必须在 laravel 的数据库目录中迁移文件,这两个主题都在我的数据库中创建了一个不同的表。第一次迁移创建了一个表,该表用于在 Id 名称中包含一列的帖子。第二次迁移创建评论表,其中有一列名为 post_id。现在the Id column in posts table is referenced keypost_id in comments table is foreign key,我如何将这两列连接在一起?

回答by Mahdi Younesi

It would be better to set unsignedIntegerfor key foreign type

最好设置unsignedInteger为外键类型

$table->unsignedInteger('category_id')->nullable();

$table->foreign('category_id')
       ->references('id')
       ->on('categories')
       ->onUpdate('cascade')
       ->onDelete('some action');;

回答by Keval Mangukiya

you use like this.

你这样用。

$table->integer('userId')->unsigned();
$table->foreign('userId')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');

回答by Kuldeep Mishra

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

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