有条件的多语言laravel播种机

时间:2018-02-08 15:36:54

标签: php mysql laravel-5 multilingual

假设我有一个表,其中包含多种语言的一组数据,以及一个引用语言表lang_code的外键code

现在我必须基于lang_code(en,es)来种子数据表。 如何根据分配的外键值使条件播种机播种,即如果lang_codeen那么种子是英文等等?

这是我在dataTableSeeder上的内容

public function run(Faker $faker)
{
    $fakerEs = Faker\Factory::create('es_ES');
    $instructionIDs = DB::table('oes_instructions')->pluck('id')->toArray();;
    $languageIDs = DB::table('oes_languages')->pluck('code')->toArray();;

    foreach (range(1,4) as $index) {
        DB::table('oes_exam_instructions_data')->insert([
        'instruction_id' => $faker->randomElement($instructionIDs),
        'locale' => $faker->randomElement($languageIDs), 
        'content' => $faker->paragraphs(10, $asText = true),   
        //Here ho do i make this based on $languageIDs => $faker->paragraphs(10, $asText = true) 
        'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
        'updated_at' => Carbon::now()->format('Y-m-d H:i:s')
        ]);
    }
}

1 个答案:

答案 0 :(得分:0)

好的很简单,但我认为使用Model Factory会更容易。

$fakerEs = Faker\Factory::create('es_ES');
    $instructionIDs = DB::table('oes_instructions')->pluck('id')->toArray();
    $languageIDs = DB::table('oes_languages')->pluck('code')->toArray();

    foreach ($instructionIDs as $instructionID) {
        foreach ($languageIDs as $languageID) {
            $data = ($languageID == 'en') ? $faker->paragraphs(6, $asText = true) : $fakerEs->paragraphs(6, $asText = true);
            DB::table('oes_instructions_data')->insert([
            'instruction_id' => $instructionID,
            'locale' => $languageID,
            'content' => $data,
            'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
            'updated_at' => Carbon::now()->format('Y-m-d H:i:s')
            ]);
        }
    }