如何在迁移中定义外键?

时间:2016-06-04 10:56:20

标签: laravel laravel-5 laravel-5.2 laravel-migrations

问题

我想在表中添加外键。当我运行看起来像这样的第一个迁移create_posts_table时:

Schema::create('posts', function(Blueprint $table) {
    $table->engine = 'InnoDB';

    $table->increments('id');
    $table->unsignedInteger('user_id')->index();

    // . . .
});

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

抛出以下错误:

  

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

     

常规错误:1215无法添加外键约束(SQL:alter table   posts在删除级联上添加约束posts_user_id_foreign外键(user_id)引用usersid

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

可能的解决方案

此问题的解决方案是在创建所有表之后使用新迁移添加外键。然而,对我来说似乎很笨拙。

问题

如何在各自表的迁移中定义外键,而不是在创建所有表后使用不同的迁移单独添加它们?

2 个答案:

答案 0 :(得分:2)

您可以在同一个迁移文件中执行多次迁移。如果您有一个posts表,您希望users表的外键,但users表尚不存在,则您必须在创建users表后在users表迁移文件中执行此操作 - 或者您必须像你说的那样做一个单独的迁移。您无法在以后的“迁移”中“保存”说明。

答案 1 :(得分:0)

以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');
    }
}
  

CreatePostsTable

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