Laravel 7: 为类别创建自定义工厂

Laravel 7: Create a custom factory for category

我正在尝试使以下类别工厂正常工作。

分类工厂

<?php

/** @var \Illuminate\Database\Eloquent\Factory $factory */

use App\Category;
use Illuminate\Support\Str;
use Faker\Generator as Faker;

$categories = ['category', 'category-2', 'category-3']

$factory->define(Category::class, function (Faker $faker) {
    return [
        'name' => // I can't use a foreach here
        'slug' => Str::slug($category),
    ];
});

我该如何实施?

我需要我的类别是独一无二的

更新使用来自@omr 的最新更新

类别工厂

use App\Category;
use Illuminate\Support\Str;
use Faker\Generator as Faker;

$categories = ['Hardware', 'Software', 'Planning', 'Tools'];

foreach ($categories as $categoryName) {
    factory(Category::class)->create([
        'name' => $categoryName,
        'slug' => Str::slug($categoryName),
    ]);
}

数据库播种器



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

 ErrorException 

  require(/home/dan/Codes/laravel/jobportal/database/factories/CategoryFactory.php): failed to open stream: Too many open files

  at vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factory.php:220
    216|         $factory = $this;
    217| 
    218|         if (is_dir($path)) {
    219|             foreach (Finder::create()->files()->name('*.php')->in($path) as $file) {
  > 220|                 require $file->getRealPath();
    221|             }
    222|         }
    223| 
    224|         return $factory;
 

谢谢

你需要 database seeder.

您的类别工厂将具有以下代码

$factory->define(Category::class, function (Faker $faker) {
    return [
        'name' => 'Name',
        'slug' => 'name',
    ];
});

并且您的数据库播种器将具有:

$categories = ['Category', 'Category 2', 'Category 3'];

foreach($categories as $category) {
  factory(App\Category::class)->create([
    'name' => $category,
    'slug' => \Str::slug($category)
  ]);
}

现在运行:php artisan db:seed(注意:这将为所有其他播种机播种,更好地使用:--class=YOUR_SEED_CLASS

你可以使用 $faker->numberBetween 从 $categories 数组中获取随机元素,然后在工厂中使用它:

$categories = ['category', 'category-2', 'category-3'];

$factory->define(Category::class, function (Faker $faker)use($categories) {
    $categoryName= $categories[$faker->numberBetween(0,count($categories)-1)];
    return [
        'name' =>$categoryName,
        'slug' => Str::slug($categoryName),
    ];
});

编辑:

如果您想生成唯一的类别名称

第一名:标准类工厂:

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

    return [
        'name' =>$faker->name,
        'slug' =>  Str::slug($faker->text(12))
    ];
});

只要你自己传递工厂字段,就不用担心类别名称和 slug 兼容性....

秒:

现在,当您创建类别时,您可以传递所需的属性,如下所示:

在数据库播种机中:

use use Faker\Generator;

....... ......

$counter=0;
while($counter<20)
{
$categoryName=$faker->text(12);
if(Category::firstWhere('name',$categoryName)==null)
{
$counter+=1;
factory(Category::class)->create(['name'=>$categoryName,'slug'=>Str::slug($categoryName)]);
}
}

不要直接使用factory('App\Category', 20)->create();没有参数,它无法帮助你...