Seed a recursive table using factories in Laravel

南楼画角 提交于 2019-12-11 05:53:41

问题


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'
   ];
});

来源:https://stackoverflow.com/questions/39811001/seed-a-recursive-table-using-factories-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!