I'm trying to use Uuids as foreign keys in my database. I want the Admin table to reference the User table.
The database is PostgreSQL, but it should work anywway.
The Users' table:
Schema::create('users', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('name', 80);
$table->string('email', 80)->unique();
...
});
My Admins' table:
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');
...
});
I also tried to assign the foreign key as String, since my Uuid trait looks like this:
<?php
namespace App\Models\Concerns;
use Illuminate\Support\Str;
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';
}
}
So my Admins' table looked like this:
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');
...
});
I always get the same errors:
[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]
and
[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]
How can I do this? The closest post I found about this was:
laravel 7 using as uuid foreign key
But somehow it doesn't work.
I'm using Laravel 8, btw.
Thank you for your help.