在Laravel 5.2中无法使用外键进行迁移

sma*_*hat 2 mysql foreign-keys database-migration laravel-5 laravel-5.2

我想创建两个表usersroles.我的代码如下:

2014_10_12_000000_create_users_table.php

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->integer('role')->unsigned();
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();

            $table->foreign('role')
                ->references('id')
                ->on('roles');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('users');
    }
}
Run Code Online (Sandbox Code Playgroud)

2016_03_09_004256_create_roles_table.php

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateRolesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('roles', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('roles');
    }
}
Run Code Online (Sandbox Code Playgroud)

当我运行时php artisan migrate出现以下错误.

[Illuminate\Database\QueryException] SQLSTATE [HY000]:常规错误:1005无法创建表trucking.#sql-1240_44(错误:150"外键约束形成错误")(SQL:alter table usersadd constraint u sers_role_foreign foreign key(role)references roles(id))

[PDOException] SQLSTATE [HY000]:常规错误:1005无法创建表trucking.#sql-1240_44(错误:150"外键约束形成错误")

Mar*_*łek 6

您应确保在roles表迁移之前运行了users表迁移.默认情况下,您在Laravel中users创建了表迁移,因此如果只更改了代码并稍后添加了roles迁移,则无法使用.您应该更改usersroles迁移文件名,以确保roles表迁移文件开头的时间戳将在users表之前.

例如,您可能有这样的情况:

2014_10_12_000000_create_users_table.php
2015_10_12_123552_create_roles_table.php
Run Code Online (Sandbox Code Playgroud)

你应该重命名文件,使其像这样:

2015_10_12_123652_create_users_table.php
2015_10_12_123552_create_roles_table.php
Run Code Online (Sandbox Code Playgroud)

当然,我假设您仅在开发期间使用这些迁移,而且还没有进行生产.