Symfony2 / Doctrine queries in loops

你离开我真会死。 提交于 2019-12-13 06:51:56

问题


I'm cleaning up some old code written by someone else because we're having problems with time-outs, especially with customers who are pushing the limits of our system.

I know this is an anti-pattern, and the code is full of variations of this:

$userIDs = [100,101,107,208, ...]; // tons of users, but not all users in a company.
$companyID = 4356;

foreach ($userIDs as $id) {
    $user = $em->getRepository('AdminBundle:Users')
                ->getUser($id, $companyId);          
    $user->removeGroup($group);
    $em->persist($user);
    $em->flush();
}

It just causes a query for every user, which makes the server time out (profiler shows hundreds of queries). Increasing the timeouts does work, but that solution doesn't scale well... and causes me to take more coffee breaks than is healthy.

What would be the correct, efficient, symfony-ey way to rewrite this into a single update query?


回答1:


Two possibilities :

  1. using a query builder with a whereIn statement , bound to the array of users id and a andWhere with the company id

  2. if the goal is to do a DELETE, and you don't make any other use of the entity after that, you can use a crafted DQL request.

if needed I can edit and put some more helpers.



来源:https://stackoverflow.com/questions/29578723/symfony2-doctrine-queries-in-loops

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!