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
Laravel::Migration - how to create foreign key by laravel migration?
提问by wr-98
How can make a referenced key
and foreign key
in laravel
by 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 key
and the post_id in comments table is foreign key
, how can I connect these two columns together?
怎样才能使 areferenced key
和foreign key
in laravel
by migrations
. 认为我必须在 laravel 的数据库目录中迁移文件,这两个主题都在我的数据库中创建了一个不同的表。第一次迁移创建了一个表,该表用于在 Id 名称中包含一列的帖子。第二次迁移创建评论表,其中有一列名为 post_id。现在the Id column in posts table is referenced key
和post_id in comments table is foreign key
,我如何将这两列连接在一起?
回答by Mahdi Younesi
It would be better to set unsignedInteger
for 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');
});