Laravel 具有动态语言环境的可翻译工厂播种

Laravel Translatable factory seeding with dynamic locales

我想在不对区域设置进行硬编码的情况下为 translatable 模型设置工厂种子。

我必须播种两个值,不是 translatable 的 slug,以及 必须将语言 table.

翻译成所有语言的标题

这是出厂文件:

$factory->define(App\Category::class, function (Faker $faker) {

 $counter = 1;
 $locales = Language::pluck('lang'); //returns hr,en,de
 $titles = [];

 foreach ($locales as $locale) {
    $titles[$locale] = [
        'title' => 'Title for category-' .$counter++. ' on '. $locale . ' language'
    ];
 }

/*
$titles = 
     "hr" => array:1 [
        "title" => "Title for category-1 on hr language"
     ]
     "en" => array:1 [
        "title" => "Title for category-2 on en language"
      ...
 */

return [
    'slug' => 'category-'.$counter++,
    $titles
];
});

这给了我一个错误:

Column not found: 1054 Unknown column 'hr'

工厂创建的查询:

insert in to category_translations (locale, hr, en, de, test, category_id) values (0, Title for category-1 on hr language, Title for category-2 on en language, Title for category-3 on de languag e, Title for category-4 on test language, 20))

经过一些试验,我找到了解决方案,这里是:

$factory->define(App\Category::class, function (Faker $faker) {

 static $counter = 1;
 $locales = Language::pluck('lang');
 $titles = array('slug' => 'CATEGORY-'.$counter);

 foreach ($locales as $locale) {
    $titles[$locale] = [
        'title' => 'Title for category-' .$counter. ' on '. $locale . ' language'
    ];
 }
 $counter++;


return $titles;
});