我想创建两个表 users
和 roles
. 我的代码如下:
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]:常规错误:1005无法创建表卡车运行 . #sql-1240_44(错误号:150“外键约束生成错误”)(SQL:alter table users add constraint u sers_role_foreign外键(角色)引用角色(id))[PDOException] SQLSTATE [HY000]:常规错误:1005无法创建表卡车运输 . #sql-1240_44(错误号:150“外键约束形成错误”)
3 回答
您应确保在
users
表迁移之前运行了roles
表迁移 . 默认情况下,在Laravel中您创建了users
表迁移,因此如果只更改了它的代码并稍后添加了roles
迁移,则它将无效 . 您应该更改users
或roles
迁移文件名,以确保roles
表迁移文件开头的时间戳将在users
表之前 .例如,您可能有这样的情况:
你应该重命名文件,使其像这样:
当然,我假设您仅在开发期间使用这些迁移,而且还没有进行 生产环境 .
尝试上面的代码 . 它工作正常