Php 运行Laravel 4迁移时发生SQL 1005错误

Php 运行Laravel 4迁移时发生SQL 1005错误,php,mysql,sql,laravel-4,Php,Mysql,Sql,Laravel 4,我正在尝试使用Laravel 4的schema builder为用户表设置一个带有外键的注释表,如下所示: Schema::create('comments', function(Blueprint $table) { $table->increments('id'); $table->integer('user_id'); $table->text('body'); $table->timestamps(); $table-&g

我正在尝试使用Laravel 4的schema builder为
用户
表设置一个带有外键的
注释
表,如下所示:

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的schema builder会为主键构建一个
int(10)
列,而不会使它们与
integer
列兼容:/

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

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

试试这个:

$table->unsignedInteger('user_id')->nullable();
$table->foreign('user_id')->references('id')->on('users');
来自laravel文档():

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

如果您使用onDelete('set null')
$table->foreign('user_id')->引用('id')->on('users')->onDelete('set null'),它可能需要将外部列设置为可空:
$table->unsignedInteger('user_id')->nullable()