如何多次遍历Laravel的工厂...?

时间:2020-02-06 02:17:26

标签: laravel factories

如何多次遍历Laravel的工厂...?

// FileFactory

$factory->define(File::class, function (Faker $faker) {
    static $imageNumber = 0;
    $imageNumber++;
    $productId = 1;
    return [
        'file_refer_type' => 1,
        'file_refer_id' => $productId,
        'name' => 'Product Name ' . $productId,
        'title' => 'Product Title ' . $productId,
        'image_type' => 1,
        'rank' => $imageNumber,
        'file_type' => 1,
        'file_size' => null,
        'file_url' => config('app.url') . 'images/products/' . $productId . '_' . $imageNumber . '.jpg',
        'thumbnail_url' => config('app.url') .'images/products/' . $productId . '_' . $imageNumber . '-thumb.jpg',
        'file_name' => null,
        'container' => null,
        'folder' => null,
        'file_extension' => null,
        'file_width' => null,
        'file_length' => null,
    ];
});

// FileTableSeeder

public function run()
{
    factory('App\File', 7)->create();
}

如果我想为两个产品创建一个循环...怎么办?
此循环仅循环1个产品7次...

像这样更新种子器是可能的...但是,这是相当重复的... 我该怎么做才能重用循环...

编辑:

//预期结果图片...

  • 第一个产品有7张图片
  • 第二个产品有2张图片

Expected results

1 个答案:

答案 0 :(得分:0)

您要的是这样的东西吗?

$factory->define(File::class, function (Faker $faker) {
    static $imageNumber = 0;

    $imageNumber++;
    $productId = 1;

    $products = [
        [
        'file_refer_type' => 1,
        'file_refer_id' => $productId,
        'name' => 'Product Name ' . $productId,
        'title' => 'Product Title ' . $productId,
        'image_type' => 1,
        'rank' => $imageNumber,
        'file_type' => 1,
        'file_size' => null,
        'file_url' => config('app.url') . 'images/products/' . $productId . '_' . $imageNumber . '.jpg',
        'thumbnail_url' => config('app.url') .'images/products/' . $productId . '_' . $imageNumber . '-thumb.jpg',
        'file_name' => null,
        'container' => null,
        'folder' => null,
        'file_extension' => null,
        'file_width' => null,
        'file_length' => null,
        ],
        [
        'file_refer_type' => 2,
        'file_refer_id' => $productId,
        'name' => 'Product Name ' . $productId,
        'title' => 'Product Title ' . $productId,
        'image_type' => 2,
        'rank' => $imageNumber,
        'file_type' => 2,
        'file_size' => null,
        'file_url' => config('app.url') . 'images/products/' . $productId . '_' . $imageNumber . '.jpg',
        'thumbnail_url' => config('app.url') .'images/products/' . $productId . '_' . $imageNumber . '-thumb.jpg',
        'file_name' => null,
        'container' => null,
        'folder' => null,
        'file_extension' => null,
        'file_width' => null,
        'file_length' => null,
        ]
    ];


    return $products[$imageNumber%2];
});