You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel种子数据如何指定UUID ID而非自动生成?

问题

我有一份来自数据库的CSV文件,其中包含UUID格式的ID,需要通过Laravel Seeder将这些指定ID导入数据库。但每次执行种子填充时,系统都会自动分配随机UUID,而非使用CSV中的ID。

Seeder代码如下:

use CsvLoader;

/**
 * @throws \Exception
 */
public function run(): void
{
    $types = $this->load('types.csv');

    foreach ($types as $type) {
        AirportType::create([
            'id'    => $type[0],
            'type'  => $type[1],
            'name'  => $type[2]
        ]);
    }
}

该Seeder能成功填充type和name字段,但ID始终是自动生成的随机值,这可能与我的初始迁移有关。迁移代码如下:

public function up()
{
    Schema::create('types', function (Blueprint $table) {
        $table->uuid('id');
        $table->string('type');
        $table->string('name');
        $table->timestamp('deleted_at')->nullable();
        $table->timestamp('created_at')->nullable();
        $table->timestamp('updated_at')->nullable();
    });

    DB::statement('ALTER TABLE types ALTER COLUMN id SET DEFAULT uuid_generate_v4();');
    
    app()->make(\Database\Seeders\TypesSeeder::class)->run();
    
}

我希望保留ID字段默认生成随机UUID的设置,但初始种子数据使用CSV中指定的ID,请问该如何实现?

解决方案

要实现保留默认UUID生成逻辑,同时让种子数据使用指定ID,可通过以下两种方式调整:

  • 方式一:修改模型的批量赋值白名单
    在AirportType模型中,将id字段添加到$fillable属性中,这样Laravel的批量赋值机制就会允许写入该字段:
class AirportType extends Model
{
    use SoftDeletes;

    protected $fillable = ['id', 'type', 'name'];
}
  • 方式二:使用forceCreate方法跳过批量赋值检查
    如果不想修改模型的$fillable配置,可在Seeder中用forceCreate替代create方法,它会强制写入指定字段,忽略批量赋值限制:
foreach ($types as $type) {
    AirportType::forceCreate([
        'id'    => $type[0],
        'type'  => $type[1],
        'name'  => $type[2]
    ]);
}

补充说明:迁移中设置的DEFAULT uuid_generate_v4()无需改动。只有当创建记录时未传入id值时,数据库才会自动生成随机UUID,完全满足你的需求。

内容的提问来源于stack exchange,提问作者jufg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 04:51:12