【问题标题】:Laravel foreign key constraint is incorrectly formed (errno 150)Laravel 外键约束格式不正确(errno 150)
【发布时间】:2020-12-16 12:49:05
【问题描述】:

谁能告诉我为什么我的外键格式不正确?

下面是部分代码:

    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

【问题讨论】:

    标签: laravel eloquent-relationship


    【解决方案1】:

    我猜你的表 posts 是在 categories 之前创建的
    因此,您不能将posts.category_id 约束到categories.id 表。

    为了解决这个问题,您应该在创建表posts之前创建表categories

    【讨论】:

    • 那么,有没有办法告诉 laravel 我想要哪个订单?顺便提一句。我想你是对的,我刚刚检查了迁移,并且在帖子表之前没有创建类别表。
    • 我知道订购迁移的唯一方法是更改​​文件名中的日期。确保运行 composer dump 以重新引用文件
    • 非常感谢。这很容易解决。
    猜你喜欢
    • 2017-04-13
    • 2019-09-17
    • 1970-01-01
    • 2021-12-30
    • 2017-05-29
    • 1970-01-01
    • 2018-06-19
    • 2018-03-02
    相关资源
    最近更新 更多