问题
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 :
using a query builder with a
whereIn
statement , bound to the array of users id and aandWhere
with the company idif 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