【问题标题】:laravel errno: 150 "Foreign key constraint is incorrectly formedlaravel errno: 150 "外键约束格式不正确
【发布时间】:2019-09-17 20:05:05
【问题描述】:

我使用以下 laravel 类别教程:

Laravel categories with dynamic deep paths

我使用下面的代码相同的迁移教程:

public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->string('slug');
            $table->integer('parent_id')->unsigned()->default(0);
            $table->timestamps();
        });

        Schema::table('categories', function (Blueprint $table) {
            $table->foreign('parent_id')->references('id')->on('categories')->onUpdate('cascade')->onDelete('cascade');
        });

    }

但我有以下错误:

SQLSTATE[HY000]: General error: 1005 Can't create table 'xxx'.'#sql-453_147' (errno: 150 "Foreign key constraint is incorrectly formed")
(SQL: alter table 'categories' add constraint 'categories_parent_id_foreign' foreign key ('parent_id') references 'categories' ('id') on delete cascade on update cascade)

感谢您的帮助

【问题讨论】:

    标签: laravel laravel-5 eloquent foreign-keys


    【解决方案1】:

    在 Laravel 中创建新表时。将生成如下迁移:

    $table->bigIncrements('id');
    

    而不是(在旧 Laravel 版本中):

    $table->increments('id');
    

    当使用 bigIncrements 时,外键需要一个 bigInteger 而不是整数。所以你的代码看起来像这样:

    public function up()
        {
            Schema::create('categories', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->string('title');
                $table->string('slug');
                $table->bigInteger('parent_id')->unsigned()->default(0);
                $table->timestamps();
            });
    
            Schema::table('categories', function (Blueprint $table) {
                $table->foreign('parent_id')->references('id')->on('categories')->onUpdate('cascade')->onDelete('cascade');
            });
    
        }
    

    【讨论】:

    • 谢谢。这是(外国)强制性的吗?
    • 如果你只有一张桌子,可能不会;但是您有可能需要将该列 id 链接到另一个不同的表中,然后它就很方便了。
    【解决方案2】:

    问题是由于列类型的不同。因此,与教程不同,您使用的是bigIncrements,这意味着 ID 为大整数,parent_id 使用默认整数。尝试将 id 更改为:

    $table->increments('id');
    

    或您的parent_id 到此:

    $table->bigInteger('parent_id')->unsigned()->default(0);
    

    【讨论】:

      猜你喜欢
      • 2017-04-13
      • 2020-12-16
      • 1970-01-01
      • 2021-12-30
      • 2017-05-29
      • 1970-01-01
      • 2018-06-19
      • 2018-03-02
      相关资源
      最近更新 更多