教义更新实体处于循环,持久还是刷新状态? [英] Doctrine update entity in loop, persist or flush?
问题描述
我有多个循环,例如:
$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();
}
}
}
所以,我下所有赌注为了进行一场比赛,每次下注我都会为该用户保存所有设备,然后我需要使用以下命令更新我的用户: $ device-> getUser()-> setBadge($ device-> ; getUser()-> getBadge()+ 1);
So, I get all bets for a match, for each bet I get all devices saved for the user, and after that I need to update my user with : $device->getUser()->setBadge($device->getUser()->getBadge() + 1);
现在,我每次都刷新,但我认为有更好的选择
For now, I flush each time but I think there is a better way, ideas ?
推荐答案
您只需要一次冲洗就可以了:
You need only one flush, out of your 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();
调用 $ this-> _em-&persist($ obj)
涉及创建一个新条目。
Calling $this->_em->persist($obj)
involves to create a new entry.
如果需要根据条目是否存在来创建或更新,请查看 EntityManager :: merge 上的doctrine-orm / en / latest / reference / working-with-objects.html#merging-entities rel = noreferrer>
If you need to create or update depending on the entry exists or not, look at EntityManager::merge
.
要保留大量条目的内存使用量,请查看批处理。
To preserve memory usage for large number of entries, look at batch processing.
注意 SensioLabs如果您的代码在循环内调用 EntityManager :: flush
,则Insight(PHP源代码质量分析)会发出警告。
Note SensioLabs insight (PHP source code quality analysis) raises a warning if your code calls EntityManager::flush
inside a loop.
这篇关于教义更新实体处于循环,持久还是刷新状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!