Summer Sale! All accounts are 50% off this week.

vincent15000's avatar

How to seed with an 'order' field in a relationship ?

Hello,

I'd like to seed with fake data. A recipe has many steps and each step has an order number (1, 2, 3, ...).

Recipe::
    factory()
    ->count(20)
    ->hasSteps(Arr::random([1, 2, 3, 4, 5, 6, 7]), function (array $attributes, Recipe $recipe) {
        return [
			'order' => // 1, 2, 3, 4, ... // => probably with a sequence but I really don't see how to do
            'recipe_id' => $recipe->id,
        ];
    })
    ->create();

Do you have any idea how to seed my order field ?

Thanks ;)

V

0 likes
8 replies
jlrdw's avatar

Perhaps just seed and then do any testing in the query. An orderby query.

Bahast7's avatar
Bahast7
Best Answer
Level 3

You can use saveMany : see bellow

Recipe::factory()->count(20)->hasSteps(Arr::random([1, 2, 3, 4, 5, 6, 7]), function (array $attributes, Recipe $recipe) {
        return [
			'order' => $order
            'recipe_id' => $recipe->id,
        ];
    })->create()->each(function ($order) {
    $Recipe->orders()->saveMany(factory(Orders::class, 5)->make());

Let me know if it works :0

vincent15000's avatar

@Bahast7 I think your suggestion is not possible for me because order is a simple number field and not a model.

Step 1 : Weight the food. Step 2 : Mix the carrots. Step 3 : Take a saucepan and fry the onions. ...

So each step has an order field to position it among the other steps.

vincent15000's avatar

@Bahast7 That's not exactly the best answer, but it helped me to think about the solution I have tested. Thank you ;).

vincent15000's avatar

@jlrdw and @bahast7

I have solved the problem without using hasSteps in the seeder. Instead of that, I'm using each() method to create each step.

If someone has the solution to do the same with hasSteps, it could be nice to try it ;).

1 like

Please or to participate in this conversation.