I’m writing a function to insert a new order with order items in it. Those items are stored in session. I need to insert all the items to order items table using Symfony for PHP.
Here what I tried:
$cart = $session->get('cart', []); foreach($cart as $shoesid => $sizes) { foreach ($sizes as $sizeid => $quantity) { $oishoe = $this->shoesRepository->findOneBy([ 'shoesid' => $shoesid ]); $oisize = $this->sizesRepository->findOneBy([ 'sizeid' => $sizeid ]); $oi = new Orderitems(); $oi->setOrderid($order); $oi->setShoesid($oishoe); $oi->setQuantity($quantity); $oi->setSizeid($oisize); } } $manager->persist($oi); $manager->flush();
But it inserts only the last item to my order items table. What code changes should I make? If you need more details, please let me know.
Advertisement
Answer
I think you should leave $manager->persist($oi)
in the foreach loop otherwise you only persist the last value.
Leave $manager->flush()
outside the loop .