
Question:
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?
Answer1:Two possibilities :
<ol><li>using a query builder with a whereIn
statement , bound to the array of users id and a andWhere
with the company id
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.
</li> </ol>if needed I can edit and put some more helpers.