php – 运行Laravel 4迁移时出现SQL 1005错误

我正在尝试使用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.

相关文章

优化MySQL数据库发布系统存储的方法有:1.mysql库主从读写分...
使用mysql的方法:在“我的电脑”→右键→“管理”→“服务”...
在mysql中查看root用户权限的方法:1.命令行启动mysql服务;...
MySQL主从复制是用来备份一个与主数据库一样环境的从数据库,...
运行mysql的方法1.启动mysql服务,在“我的电脑”→右键→“...
开启mysql的方法1.可以通过快捷键win+r,输入cmd,打开窗口,...