Laravel 7 如何使用 UUID 作为外键

7

我有两个表,在这两个表中,我都使用 UUID 生成一个 ID。然后,我试图在第二个表中将一个 ID 用作外键。如下所示:迁移确实接受了我的操作,但是当我插入数据时,却出现了以下错误。

Illuminate/Database/QueryException with message 'SQLSTATE[01000]: Warning: 1265 Data truncated for column 'userId' at row 1 

这是我的第一张表格:

       Schema::create('users', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->string('userName')->unique();
            $table->string('email')->unique();
            $table->boolean('isVerified')->default(false);
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });

带有外键的第二个表

Schema::create('tableTwo', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->unsignedBigInteger('userId');
            $table->foreign('userId')
            ->references('id')
            ->on('users')
            ->onDelete('cascade');
            $table->timestamps();
        });

当这个错误发生时,你能否分享你尝试插入的数据? - Nico Haase
3个回答

10

你正在将整数列映射到uuid列,但由于SQL约束不同类型之间不能完成映射...

你应该进行修改:

  $table->unsignedBigInteger('userId');

to

 $table->uuid('userId')->nullable(false);

我按照你说的做了,现在可以插入数据了,但是这两个表还没有连接起来。我可以在没有在表一中添加用户的情况下向表二中添加数据!它应该显示没有此ID的用户。 - mdeveloper
你已经移除了以下代码吗:$table->foreign('userId')->references('id')->on('users')->onDelete('cascade'); - OMR
不,我没有删除 $table->foreign('userId')->references('id')->on('users')->onDelete('cascade'); 为什么我需要删除它呢? - mdeveloper
谢谢您的回复,但我有一个问题,我应该在模型中添加belongs to或has many语句吗? - mdeveloper
外键不起作用,我知道它有很多并且属于某些东西,但是这些表根本没有连接。 - mdeveloper
显示剩余3条评论

3

将您的代码从以下方式更改

$table->unsignedBigInteger('userId');

为了

$table->foreign('userId')

如果您使用 Laravel 8,您可以像这样输入:
$table->foreignUuid('user_id');

我遇到了同样的问题,但我已经尝试了所有方法,但仍然显示相同的错误。我已经尝试了foreignUuid()、foreign(),但仍然没有用。 - M Andre Juliansyah

1
如果有人看到这个问题,现在 Laravel 允许使用 foreignUuid 方法:
$table->foreignUuid('userId')
    ->constrained()
    ->cascadeOnDelete();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接