lundi 12 novembre 2018

Seeding Laravel many to many table with data

I have 3 tables; orders, products and order_product. I am trying to seed the order_product pivot table using the Seeder class.

This is what I have in my code;

$productArray = \Illuminate\Support\Facades\DB::table('products')->pluck('id')->toArray();

factory(PetroSoft\Order::class, 60)->create()->each(function ($order) use ($productArray)  {
  $randomPickings = mt_rand(1, 4);
  $order->products()->sync(array_rand($productArray), $randomPickings);
});

I want attach product ids from the $productArray so an order can have, say, 1,2,3,4 or 5 products attached after seeding. Currently, I get this error when I run the seeder.

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or 
update a child row: a foreign key constraint fails 
(`petrosoft`.`order_product`, CONSTRAINT 
`order_product_product_id_foreign` FOREIGN KEY (`product_id`) 
REFERENCES `products` (`id`) ON DELETE CASCADE) (SQL: insert into 
`order_product` (`order_id`, `product_id`) values (2, 0))

There's no product with id 0. I'm guessing it's picking the indexes instead of the values. How do I get the values selected/picked instead? Thanks.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire