首页 > 解决方案 > Laravel 与 UUID 的同表关系

问题描述

我的 Laravel 迁移有一些问题。我正在尝试从同一个表中添加可为空的父键。像这样:

Schema::create('categories', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->string('name');
            $table->uuid('parent_id')->nullable();

            $table->foreign('parent_id')->references('id')->on('categories')->onDelete('cascade');
            $table->timestamps();
        });

它总是回来

SQLSTATE[HY000]:一般错误:1005 无法创建表 ecommercecategories(errno: 150 "Foreign key constraint is wrongly forms") (SQL: alter table categoriesadd constraint categories_parent_id_foreignforeign key ( parent_id) references categories( id) on delete cascade)

但我在类似的项目中有它,但有 id,它的工作原理是这样的:

Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('parent_id')->nullable();
            $table->string('name');
            $table->timestamps();

            $table->foreign('parent_id')->references('id')->on('categories');
        });

但是如何使它与 uuid 一起工作呢?

标签: phpmysqllaravel

解决方案


在第一次迁移创建categories表后,在第二次迁移定义外键,如下所示:

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

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

上面的代码用Laravel 8.25.0&测试MariaDB 10.4.14


推荐阅读