【问题标题】:Putting array as arguments to Laravel's factory that is repeated将数组作为参数传递给 Laravel 的重复工厂
【发布时间】:2018-08-01 11:24:01
【问题描述】:
$categoryTitles = [
  'Games',
  'Running',
  'Hacking',
  'Walking',
];

$categoryDescriptions = [
  'this is nice',
  'kinda cool',
  'really good',
  'fine',
];

$categories = factory(App\Category::class, 4)->create([
  'title' => array_pop($categoryTitles),
  'description' => array_pop($categoryDescriptions),
]);

通过查看上面的代码,您可能会知道我要做什么。

我想用数组中定义的自定义项运行 4 次工厂。

但它不起作用,因为它从两个数组中获取最后一个项目并且正在处理它们 4 次。直到数组为空时才需要 next 和 next。

我不知道该怎么做。我认为代码解释了我想要做什么。

【问题讨论】:

    标签: php laravel laravel-5 eloquent factory


    【解决方案1】:

    你需要调用工厂的 create() 方法 4 次:

    $categories = [];
    for ($i = 0; $i < 4; ++$i) {
      $categories[] = factory(App\Category::class)->create([
        'title' => $categoryTitles[$i],
        'description' => $categoryDescriptions[$i],
      ]);
    }
    

    【讨论】:

    • 没有别的办法了吗?尤其是 Laravel 的方式?
    • 还有很多其他的方法,我认为这是最简单和最易读的一种。 create() 方法要求您传递要在默认工厂定义中覆盖的属性数组。如果你想创建 4 个不同的对象,你需要传递 4 个不同的数据集,但是 create() 只允许你传递一个数据集 - 这就是为什么你只需要调用它 4 次。
    【解决方案2】:

    jedrzej.kurylo 是对的。您可以利用Laravel Collections 并执行以下操作:

    $categories = collect([
        ['title' => 'Games',   'description' => 'this is nice'],
        ['title' => 'Running', 'description' => 'kinda cool'],
        ['title' => 'Hacking', 'description' => 'really good'],
        ['title' => 'Walking', 'description' => 'fine'],
    ])->mapWithKeys(function ($category) {
        return factory(App\Category::class)->create([
            'title' => $category['title'],
            'description' => $category['description']
        ]);
    });
    

    【讨论】:

      猜你喜欢
      • 2023-03-06
      • 2015-11-29
      • 1970-01-01
      • 2012-08-29
      • 2013-07-07
      • 2021-07-11
      • 2014-12-27
      • 2013-11-11
      • 1970-01-01
      相关资源
      最近更新 更多