我想創建兩個表users
和roles
。我的代碼如下所示:無法在Laravel 5.2中使用外鍵遷移
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');
}
}
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');
}
}
當我運行php artisan migrate
下面的錯誤出現。
[Illuminate\Database\QueryException] SQLSTATE[HY000]: General error: 1005 Can't create table
trucking
.#sql-1240_44
(errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter tableusers
add constraint u sers_role_foreign foreign key (role
) referencesroles
(id
))[PDOException] SQLSTATE[HY000]: General error: 1005 Can't create table
trucking
.#sql-1240_44
(errno: 150 "Foreign key constraint is incorrectly formed")
哇它的作品!好主意!謝謝哥們。 – smartrahat
@smartrahat沒問題。您需要記住,您可以只將外鍵創建到現有表中,因此有時您需要創建2個遷移(無外鍵),並在第3次遷移時在表之間添加外鍵。 –
感謝您的提示。我會記住它。 – smartrahat