Laravel外键约束格式不正确errno 150

问题描述

有人可以告诉我为什么我得到的外键格式不正确吗?

这是代码的一部分:

    public function up()
    {
        Schema::create('posts',function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->string('title');
            $table->text('content');
            $table->string('featured');
            $table->string('slug');
            $table->foreignId('category_id')->constrained()->onDelete('cascade');

            $table->softDeletes();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }

这是类别表:

    public function up()
    {
        Schema::create('categories',function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('slug');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('categories');
    }

注意

仅针对类别,不会删除“ user_id”外键的错误。

解决此问题

只需更改数据库/迁移的日期-例如,如果希望在发布表进行此更改之前创建类别,则进行迁移:

2020_08_06_172006_create_posts_table.php 2020_08_09_172006_create_categories_table.php

从迁移类别的更改日期 2020_08_09 ,例如 2020_ 07 _09

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)