【问题标题】:Laravel Same Table Relation with UUIDLaravel 与 UUID 的同表关系
【发布时间】:2021-05-08 01:01:52
【问题描述】:

我的 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 无法创建表 ecommerce.categories (errno: 150 "外键约束为 格式不正确") (SQL: alter table categories add constraint categories_parent_id_foreign 外键 (parent_id) 引用 categories (id) 删除级联)

但我在类似的项目中有它,但有 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 让它工作呢?

【问题讨论】:

  • 你需要在你的模型上定义主键public $incrementing = false; protected $keyType = 'string';
  • 我没有模型,只是迁移

标签: php mysql laravel


【解决方案1】:

在第一次迁移创建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.0MariaDB 10.4.14

测试

【讨论】:

  • ->nullable(false) 将更改初始配置。
【解决方案2】:

主要问题是外键只能应用于primary keysunique columns。因此,您可以通过执行以下操作将 uuid 列定义为主键:

$table->primary('<UUID COLUMN NAME>');

【讨论】:

    猜你喜欢
    • 2019-10-01
    • 1970-01-01
    • 2019-07-29
    • 2021-01-09
    • 2019-10-15
    • 1970-01-01
    • 2020-09-16
    • 2019-12-03
    • 2018-10-20
    相关资源
    最近更新 更多