samedi 1 octobre 2016

Seed a recursive table using factories in Laravel

I have a recursive table in my Laravel project to handle a dynamic menu. For testing purposes I need to seed that table with random elements.

The name is not the problem (a random name would be okay). The main thing is how to generate the parent_id numbers. I'll show an example:

+---------------------------+
| id  | name    | parent_id |
+---------------------------+
| 1   | animals | 0         |
|---------------------------|
| 2   | food    | 0         |
|---------------------------|
| 3   | dog     | 1         |
|---------------------------|
| 4   | potato  | 2         |
|---------------------------|
| 5   | monkey  | 1         |
+---------------------------+

I don't want to generate a random number, because some entries of the table would not have any associated parent. And since the id is incremental, the parent_id must be associated with some id.

I've created the factory for the first level (the parent_id = 0). But I don't know how to continue now.

$factory->defineAs(App\Section::class, 'firstLevelMenu', function($faker) {
   return [
       'name' => $faker->unique->randomElement([
           'animals',
           'food'
       ]),
       'parent_id' => '0'
   ];
});



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire