Doctrine update object in a loop, save or hide?

I have a few loops like:

$bets = $this->em->getRepository('AppBundle:Bet')->getBetsForMatch($match_id); foreach ($bets as $key => $bet) { $devices = $this->em->getRepository('AppBundle:Device')->findBy(array('user' => $bets->getUser())); foreach ($devices as $key => $device) { //HERE I SEND A PUSH NOTIFICATION if($this->rms_push->send($message)){ $device->getUser()->setBadge($device->getUser()->getBadge() + 1); $this->em->flush(); } } } 

So, I get all the bets to match, for each bet I get all the devices saved for the user, and after that I need to update my user: $device->getUser()->setBadge($device->getUser()->getBadge() + 1);

At the moment, I erase every time, but I think there is a better way, ideas?

+6
source share
1 answer

You need only one flash from the loop:

 foreach ($bets as $key => $bet) { $devices = $this->em->getRepository('AppBundle:Device')->findBy(array('user' => $bets->getUser())); foreach ($devices as $key => $device) { //HERE I SEND A PUSH NOTIFICATION if($this->rms_push->send($message)){ $device->getUser()->setBadge($device->getUser()->getBadge() + 1); } } } $this->em->flush(); 

Calling $this->_em->persist($obj) involves creating a new record.

If you need to create or update depending on an existing record, look in EntityManager::merge .

To save memory usage for a large number of records, review batch processing .

Note SensioLabs analysis (PHP source code quality analysis) raises a warning if your code calls EntityManager::flush inside a loop.

+5
source

All Articles