微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.

原文地址:https://www.jb51.cc/mysql/433181.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐