I have two tables named Order and OrderItem. While creating data in the Order table, I am trying to enter data into the OrderItem table at the same time. The codes are as follows;
OrderSeeder.php
public function run() { Order::factory()->count(30)->create() ->each(function (Order $order) { Order::factory( OrderItem::class, random_int(1, 5))->create([ 'order_id' => $order->id, ]); }); }
OrderFactory.php
public function definition() { return [ 'first_name' => $this->faker->name(), 'last_name' => $this->faker->lastName(), 'email' => $this->faker->email(), ]; }
OrderItemFactory.php
public function definition() { return [ 'product_title' => $this->faker->text(30), 'price' => $this->faker->numberBetween(10.100), 'quantity' => $this->faker->numberBetween(1, 5), ]; }
Advertisement
Answer
When I updated the page like this, the problem was solved.
OrderSeeder.php
public function run() { Order::factory(10) ->create() ->each(function ($order) { OrderItem::factory(random_int(1,3)) ->create([ 'order_id' => $order->id, ]); }); }
You can use it as a resource when you encounter a similar error..