我对使用 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');
});
}
在 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(),
]);