问题
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