Laravel factory,我的数据来自数组,不是随机的

Laravel factory, my data is from an array, not random

告诉我如何添加不是随机数据,而是工厂中的特定数据。例如,我想创建 3 个工厂并用数组中的所有值填充字段。

这里我用数据库中的随机 ID 创建了 3 个工厂。我需要创建 3 个工厂来获得 basic_section_id = 1, basic_section_id = 2, basic_section_id = 3.... 而不是每个工厂的随机 ID。请告诉我。

class BasicCardFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'basic_section_id' => BasicSection::all()->random()->id
        ];
    }
}

class BasicSectionSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $basicSections = BasicSection::factory(3)->create();
    }
}

If you would like to override some of the default values of your models, you may pass an array of values to the make method. Only the specified attributes will be replaced while the rest of the attributes remain set to their default values as specified by the factory: (Laravel Docu - https://laravel.com/docs/9.x/database-testing#overriding-attributes)

 $user = User::factory()->make([
     'name' => 'Abigail Otwell',
 ]);

在你的情况下会是这样的:


class BasicSectionSeederFactory extends Factory{
   public function definition()
   {
      return [
         'property1' => $this->fake->name(),
         'notRandom' => "foobar",
         //...
      ];
   }
}


 $seeder = BasicSectionSeeder::factory()->make( [
  //your properties go here ...
 ]);

你需要和工厂一起“造”模型。这就是线索。

稍微检查一下整个文档,以获得所需的所有约定:https://laravel.com/docs/9.x/database-testing#factory-and-model-discovery-conventions

如果您使用 laravel 8+,工厂的 Sequence class 可能会稍微简化您的代码。在您的情况下,示例可能是:

class BasicSectionSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $basicSections = BasicSection::factory()
                                     ->count(3)
                                     ->sequence(fn ($sequence) => ['basic_section_id' => $sequence->index + 1])
                                     ->create();
    }
}

更多信息你可以查看官方文档:https://laravel.com/docs/9.x/database-testing#sequences