laravel - 如何多次循环遍历 Laravel 中的工厂...?
问题描述
如何多次循环遍历 Laravel 中的工厂...?
// 文件工厂
$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();
}
如果我想为 2 个产品创建一个循环怎么办...?
此循环仅循环 1 个产品 7 次...
可以像这样更新播种机......但是,这是非常重复的......我能做些什么来重用循环......
编辑:
//预期结果图像...
- 第一个产品有 7 张图片
- 第二个产品有 2 张图片
解决方案
你问这样的事情吗?
$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];
});
推荐阅读
- c# - 如何提高 dotnet ef core 中的价值转换性能?
- javascript - 即使在设置唯一键时也对 redux 重复键做出反应
- regex - 在 perl 中读取日志文件并在方括号中找到值
- authentication - Kerberos 中的 401 未授权响应
- java - 使用 RestTemplate 发送 Multipart 文件
- bigcommerce - 基石有没有办法通过 url 注入 html?
- python - 当部分单词包含特殊字符时,Python正则表达式匹配单词边界
- excel - 使用 For 循环选择 Access 中的特定字段并将它们粘贴到 Excel
- java - 当我的布局中的 NestedScrollView 在其下方添加更多小视图时,它变得迟缓
- django - 使用 Django 和 Angular 进行 Windows 身份验证?