SQL 1005在运行Laravel 4迁移时出错


SQL 1005 error when running Laravel 4 migration

我正试图用Laravel 4的模式生成器设置一个comments表,其中包含users表的外键,如下所示:

Schema::create('comments', function(Blueprint $table)
{
    $table->increments('id');
    $table->integer('user_id');
    $table->text('body');
    $table->timestamps();
    $table->foreign('user_id')->references('id')->on('users');
});

但当我运行迁移时,我会收到以下错误消息:

[Exception]
SQLSTATE[HY000]: General error: 1005 Can't create table 'streamr.#sql-16fc_89' (errno: 150)
(SQL: alter table `comments` add constraint comments_user_id_foreign foreign key (`user_id`) references `users` (`id`)) (Bindings: array ())

据我所知,这是因为users表的id列是int(10),而$table->integer('user_id')使int(11)列由于列类型不兼容而导致外键失败。然而,当我试图设置我正在创建的整数列的长度时,它不起作用:

$table->integer('user_id', 10);

有什么办法绕过这个吗?我觉得奇怪的是,Laravel的模式构建器将为主键构建一个int(10)列,而不使它们与integer列兼容:/

编辑:我还确保了表是InnoDB,它们确实是。

$table->increments('id')生成一个无符号整数。设置外键时,整数与无符号整数不兼容。

试试这个:

$table->unsignedInteger('user_id')->nullable();
$table->foreign('user_id')->references('id')->on('users');

来自laravel文档(http://laravel.com/docs/schema#foreign-按键):

注意:创建引用递增整数的外键时,请记住始终使外键列无符号。