在 Laravel 中间表中实现 UUID 作为主键

问题描述 投票:0回答:1

我对使用 UUID 作为中间表中的主键感兴趣。我知道将

use Illuminate\Database\Eloquent\Concerns\HasUuids;
use HasUuids;
添加到模型中可以实现此目的。但是,由于我没有或不需要中间表的模型,因此我不确定是否可以类似地自动创建 UUID。在中间表中创建条目时是否需要手动生成 UUID?

这是我的迁移文件的样子:

public function up(): void {
    Schema::create('post_user', function (Blueprint $table) {
        $table->uuid('id')->primary();
        $table->timestamps();
        $table->string('title');
        $table->string('body');
    });
}
php laravel eloquent uuid
1个回答
0
投票

在 Laravel 中,可以使用

HasUuids
特性自动为模型生成 UUID。但是,对于没有模型的中间表,您需要在创建条目时手动生成 UUID。一种方法是在将数据插入表时使用 Laravel 内置的
Str::uuid()
方法。

DB::table('post_user')->insert([
    'id' => (string) Str::uuid(),
    'title' => $title,
    'body' => $body,
    'created_at' => now(),
    'updated_at' => now(),
]);
© www.soinside.com 2019 - 2024. All rights reserved.