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

Laravel 9:如何向Factory传递语言区域参数生成多语言测试数据

多语言书籍测试数据生成方案

1. 修正BookFactory,支持传入语言区域参数

首先调整工厂类,让它能接收语言区域代码,同时自动关联对应的language_id,还要修复content字段的数组转字符串问题:

class BookFactory extends Factory
{
    // 自定义状态方法,用于指定生成书籍的语言
    public function forLanguage(string $locale)
    {
        // 根据语言区域的前2位匹配Languages表的code字段,不存在则创建对应语言记录
        $language = \App\Models\Language::firstOrCreate(
            ['code' => substr($locale, 0, 2)],
            ['name' => $this->faker->languageName()]
        );

        return $this->state(fn () => [
            'language_id' => $language->id,
            'title' => fake($locale)->sentence(rand(3, 7)),
            'content' => implode(' ', fake($locale)->sentences(rand(5, 11))),
        ]);
    }

    // 默认生成英文书籍
    public function definition()
    {
        $language = \App\Models\Language::firstOrCreate(
            ['code' => 'en'],
            ['name' => 'English']
        );

        return [
            'language_id' => $language->id,
            'title' => fake('en_US')->sentence(rand(3, 7)),
            'content' => implode(' ', fake('en_US')->sentences(rand(5, 11))),
        ];
    }
}

2. 在Seeder中调用工厂生成多语言数据

修改DatabaseSeeder,通过调用工厂的自定义状态方法,指定不同语言区域代码生成对应数据:

class DatabaseSeeder extends Seeder
{
    public function run()
    {   
        // 生成10本默认英文书籍
        \App\Models\Book::factory(10)->create();

        // 生成10本德文书籍
        \App\Models\Book::factory(10)->forLanguage('de_DE')->create();

        // 生成10本西班牙文书籍
        \App\Models\Book::factory(10)->forLanguage('es_ES')->create();

        // 批量生成多种语言书籍
        $locales = ['fr_FR', 'ja_JP', 'zh_CN'];
        foreach ($locales as $locale) {
            \App\Models\Book::factory(8)->forLanguage($locale)->create();
        }
    }
}

补充:若Languages表已有预设数据

如果你的languages表已经预先填充了语言记录,只需修改forLanguage方法,直接查询已有记录即可,避免重复创建:

public function forLanguage(string $locale)
{
    $languageCode = substr($locale, 0, 2);
    // 查找已有语言记录,不存在则抛出异常
    $language = \App\Models\Language::where('code', $languageCode)->firstOrFail();

    return $this->state(fn () => [
        'language_id' => $language->id,
        'title' => fake($locale)->sentence(rand(3, 7)),
        'content' => implode(' ', fake($locale)->sentences(rand(5, 11))),
    ]);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 05:10:31