我正在尝试使用Laravel 4的架构构建器为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->整数(‘user_id’)使得int(11)列导致外键失败,因为不兼容的列类型.但是,当我尝试设置整数列的长度时,我正在创建它不起作用:
$table->integer('user_id',10);
有没有办法解决这个问题?对我来说很奇怪,Laravel的架构构建器将为主键构建一个int(10)列,而不是使它们与整数列兼容:/
编辑:我也确保表是InnoDB,他们是.
最佳答案
$table-> incrementments(‘id’)生成无符号整数.设置外键时,整数与无符号整数不兼容.
试试这个:
$table->unsignedInteger('user_id')->nullable();
$table->foreign('user_id')->references('id')->on('users');
来自laravel docs(http://laravel.com/docs/schema#foreign-keys):
Note: When creating a foreign key that references an incrementing integer,remember to always make the foreign key column unsigned.