Symfony2 / Doctrine查询循环 [英] Symfony2 / Doctrine queries in loops

查看:187
本文介绍了Symfony2 / Doctrine查询循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在清理别人写的旧代码,因为我们遇到超时问题,特别是那些正在推动系统限制的客户。

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();
}

它只是为每个用户产生一个查询,这会使服务器超时( profiler显示数百个查询)。增加超时功能是有效的,但该解决方案不能很好地扩展...并导致我比健康更多的咖啡休息。

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.

什么是正确的,

推荐答案

两种可能性:


  1. 使用具有 whereIn 语句的查询构建器,绑定到用户数组id和与公司ID

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

如果目标是执行DELETE,你不会任何其他使用实体之后,您可以使用精心设计的DQL请求。

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.

这篇关于Symfony2 / Doctrine查询循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆