1

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

A random element of faker library will be okay for the menu name. The problem is how to generate the parent_id numbers that match with any element of that menu table. I'll show you an example:

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

The random number won't work here, because some entries of the table would't have any associated parent. And since the id is incremental, the id will change anytime. 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'
   ];
});
alexhoma
  • 342
  • 1
  • 7
  • 19
  • I think you could do something like this: `'parent_id' => collect([0])->merge(App\Section::lists('id'))->random()` – Ohgodwhy Oct 01 '16 at 20:14
  • @Ohgodwhy I tried it (I didn't know `lists` was an Eloquent method!). It almost works, except for the '0'. In some cases, `parent_id` is 0 and I don't want it. Is there any way to avoid the '0'? If you have the answer jut post it, i'll will count it as a valid anyway, this solved my problem. – alexhoma Oct 01 '16 at 21:48
  • What are the circumstances at which you'd like to ignore the `0`? – Ohgodwhy Oct 02 '16 at 01:39
  • @Ohgodwhy The first level menu elements have `parent_id` setted with a 0. And I would use the enclosure function of the example for this. Then the second/third/fourth... level menu elements must have any other `id` number of table as a `parent_id` elements except 0. Because they're not on the first level menu. – alexhoma Oct 02 '16 at 15:54
  • I think you could accomplish this with a ternary. `'parent_id' = > App\Section::all()->count() > 2 ? App\Section::lists('id')->random() : 0` – Ohgodwhy Oct 02 '16 at 19:04

0 Answers0