Laravel5.5. migrate 提示外键约束错误?

In Connection.php line 664:

SQLSTATE[HY000]: General error: 1005 Can't create table n_fruit.#sql-3fa0_23 (errno: 150 "Foreign key constrain
t is incorrectly formed") (SQL: alter table posts add constraint posts_comment_id_foreign foreign key (comment _id) references comments (id) on delete cascade)

In Connection.php line 458:

SQLSTATE[HY000]: General error: 1005 Can't create table n_fruit.#sql-3fa0_23 (errno: 150 "Foreign key constrain
t is incorrectly formed")

Process finished with exit code 1 at 13:53:34.
Execution time: 12,000 ms.

请问给位朋友这要怎么处理,下面是表字段设置
posts表
$table->integer('comment_id')->unsigned()->comment('评论id');
$table->integer('category_id')->unsigned()->comment('所属分类id');
$table->foreign('comment_id')
->references('id')
->on('comments')
->onDelete('cascade');

        $table->foreign('category_id')
            ->references('id')->on('categorys')
            ->onDelete('cascade');
        $table->timestamps();

comments表是存在的

xtn
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 8
leo

外键类型要一致

$table->unsignedInteger('comment_id')
6年前 评论
xtn

@leo 您好 还是一样的错误!



$table->unsignedInteger('comment_id')->comment('评论id');
            $table->unsignedInteger('category_id')->comment('所属分类id');
            $table->foreign('comment_id')
                  ->references('id')
                  ->on('comments')
                  ->onDelete('cascade');

            $table->foreign('category_id')
                ->references('id')
                ->on('categorys')
                ->onDelete('cascade');
6年前 评论
xtn

@leo 我猜想是不是和migirate创建的时间先后顺序有关 我再数据库里面是可以创建外键约束的 但是就是通过命令不可以 还有其他表通过migrate:fresh是可以通过命令创建约束 我看了下时间comment表实在post表后创建的!

6年前 评论
leo

@xtn 好好复习下数据库吧

6年前 评论

你好怎么解决的?

5年前 评论

@knife Leo 已经说了,你先检查一下你外键类型是否一致

5年前 评论
DivingPig 4年前

试试 在 migrate 之前去 设置 mysql 不检查外键约束
1.set FOREIGN_KEY_CHECKS=0;
2.迁移数据文件
3.set FOREIGN_KEY_CHECKS=1; #在导入后恢复检查外键约束

5年前 评论

我也遇到同样的问题,经过验证,确实是Products和product_skus两个表的迁移文件顺序导致的。Products表迁移文件必须在Product_skus表迁移文件前面执行,可能是后者依赖前者。

5年前 评论
DivingPig 4年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!