【发布时间】:2016-06-24 06:37:47
【问题描述】:
我想创建两个表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 时出现以下错误。
[照亮\数据库\查询异常] SQLSTATE[HY000]: 一般错误: 1005 Can't create table
trucking.#sql-1240_44(errno: 150 "外键约束格式不正确") (SQL: alter tableusersadd constraint u sers_role_foreign 外键 (role) 引用roles(id))[PDO异常] SQLSTATE[HY000]: 一般错误: 1005 无法创建表
trucking.#sql-1240_44(errno: 150 "外键约束格式不正确")
【问题讨论】:
标签: mysql laravel-5 foreign-keys database-migration laravel-5.2