Laravel 如何在迁移中定义外键? 问题

Laravel 如何在迁移中定义外键? 问题,laravel,laravel-5,laravel-5.2,laravel-migrations,Laravel,Laravel 5,Laravel 5.2,Laravel Migrations,我想向表中添加外键。当我第一次运行我的迁移create\u posts\u表时如下所示: Schema::create('posts',函数(Blueprint$table){ $table->engine='InnoDB'; $table->increments('id'); $table->unsignedInteger('user_id')->index(); // . . . }); Schema::table('posts',函数(Blueprint$table) { $table->

我想向表中添加外键。当我第一次运行我的迁移
create\u posts\u表时
如下所示:

Schema::create('posts',函数(Blueprint$table){
$table->engine='InnoDB';
$table->increments('id');
$table->unsignedInteger('user_id')->index();
// . . .
});
Schema::table('posts',函数(Blueprint$table)
{
$table->foreign('user_id')->references('id'))
->on('users')->onDelete('cascade');
});
将引发以下错误:

[Illumb\Database\QueryException]SQLSTATE[HY000]:

一般错误:1215无法添加外键约束(SQL:alter table
posts
add constraint
posts\u user\u id\u foreign
外键(
user\u id
)引用
users
id
)删除级联)

这是因为尚未创建
用户
,因此无法在
posts
表上创建用户引用外键

可能的解决办法 此问题的解决方案是在创建所有表后,通过新的迁移添加外键。然而,它对我来说似乎很笨重

问题
如何在各自表的迁移中定义外键,而不是在创建了所有表之后通过不同的迁移分别添加外键?

您可以在同一迁移文件中执行多个迁移。如果您有一个posts表,其中需要用户表的外键,但用户表尚不存在,则必须在创建用户表后在用户表迁移文件中执行此操作,或者必须执行单独的迁移,如您所说。您不能为以后的迁移“保存”说明。

以laravel的方式为不同的表保留单独的迁移文件,包括索引、主键和外键

CreateUsersTable

创建后稳定


那么,就我所知,这些是唯一的选择?恐怕是的。谢谢你的回答。为了清楚起见,迁移是按创建顺序运行的。您将看到每个迁移文件的文件名开头都有一个日期/时间。在创建所需表后设置的迁移文件中设置外键;在设置完所有创建的表迁移后,创建一个单独的迁移,或者重新排列与迁移文件相关联的时间戳(尽管不建议这样做-而是重新开始)。
class CreateUsersTable extends Migration
{

    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('email');
        $table->string('password', 60);            
        $table->enum('status', ['0', '1'])->default('0');
        $table->rememberToken();
        $table->nullableTimestamps();

        $table->unique('email');

        });
    }

    public function down()
    {
        Schema::drop('users');
    }
}
class CreatePostsTable extends Migration
{

    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();         

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

    public function down()
    {
        Schema::drop('posts');
    }
}