Eloquent Uuids作为外键



我正试图在数据库中使用Uuid作为外键。我希望Admin表引用User表。

数据库是PostgreSQL,但它无论如何都应该工作。

用户表:

Schema::create('users', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('name', 80);
$table->string('email', 80)->unique();
...
});

我的管理员表:

Schema::create('administrators', function (Blueprint $table) {
$table->increments('id');
$table->uuid('fk_user_id');
$table->foreign('fk_user_id')->references('id')->on('users')->onDelete('cascade');
...
});

我还尝试将外键分配为String,因为我的Uuid特性如下所示:

<?php
namespace AppModelsConcerns;
use IlluminateSupportStr;
trait UsesUuid
{
protected static function bootUsesUuid()
{
static::creating(function ($model) {
if (! $model->getKey()) {
$model->{$model->getKeyName()} = (string) Str::uuid();
}
});
}
public function getIncrementing()
{
return false;
}
public function getKeyType()
{
return 'string';
}
}

所以我的管理员表是这样的:

Schema::create('administrators', function (Blueprint $table) {
$table->increments('id');
$table->string('fk_user_id', 36);
$table->foreign('fk_user_id')->references('id')->on('users')->onDelete('cascade');
...
});

我总是遇到同样的错误:

[2020-10-15 10:52:44] local.ERROR: SQLSTATE[42804]: Datatype mismatch: 7 ERROR:  foreign key constraint "administrators_fk_user_id_foreign" cannot be implemented
DETAIL:  Key columns "fk_user_id" and "id" are of incompatible types: character varying and uuid. (SQL: alter table "administrators" add constraint "administrators_fk_user_id_foreign" foreign key ("fk_user_id") references "users" ("id") on delete cascade) {"exception":"[object] (Illuminate\Database\QueryException(code: 42804): SQLSTATE[42804]: Datatype mismatch: 7 ERROR:  foreign key constraint "administrators_fk_user_id_foreign" cannot be implemented
DETAIL:  Key columns "fk_user_id" and "id" are of incompatible types: character varying and uuid. (SQL: alter table "administrators" add constraint "administrators_fk_user_id_foreign" foreign key ("fk_user_id") references "users" ("id") on delete cascade) at C:\MyFolder\Dev\MyProjects\Laravel\VitruvianShield\vitruvianshield\vendor\laravel\framework\src\Illuminate\Database\Connection.php:669)
[stacktrace]

[previous exception] [object] (PDOException(code: 42804): SQLSTATE[42804]: Datatype mismatch: 7 ERROR:  foreign key constraint "administrators_fk_user_id_foreign" cannot be implemented
DETAIL:  Key columns "fk_user_id" and "id" are of incompatible types: character varying and uuid. at C:\MyFolder\Dev\MyProjects\Laravel\VitruvianShield\vitruvianshield\vendor\laravel\framework\src\Illuminate\Database\Connection.php:463)
[stacktrace]

我该怎么做?我发现的最接近这一点的帖子是:

laravel 7用作uuid外键

但不知怎么的,它不起作用。

我正在使用Laravel 8,顺便说一下

谢谢你的帮助。

在这里试试这个:

Schema::create('administrators', function (Blueprint $table) {
...
$table->string('fk_user_id');
...
});
```

相关内容

  • 没有找到相关文章

最新更新