使用doctrine更新数据库中的多条记录的最佳方法是什么,symfony2?
我收到需要更新的记录ids数组。
我想为每条记录分配从接收到的数组到列show_order的索引。因此,如果我收到数组$array = array(22,1,5,10),那么我想这样做
$i = 0;
foreach($array as $a) {
$record = $this->getDoctrine->getRepository('AcmeBundle:SomeEntity')->findOneById($a);
if ($record != null) $record->setOrder($i++);
}
$this->getDoctrine()->getEntityManager()->flush();但这是一种可怕的方式,因为我对每条记录执行一次SELECT,所以查询的数量是O(n)。
如何做得更好?
发布于 2012-01-07 23:58:35
就像..。
foreach ($repo->findById($ids) as $obj) {
$obj->setOrder(array_search($obj->getId(), $ids));
}
$em->flush();发布于 2012-04-03 21:26:40
所以这仍然是0(n),但它是1n而不是2n。为了避免不必要的选择,我使用custom repository class和原理查询构建器解决了这个问题,如下所示:
namespace BRS\PageBundle\Repository;
use Doctrine\ORM\EntityRepository;
class ContentRepository extends EntityRepository
{
public function reorder($content)
{
$em = $this->getEntityManager();
$count = 0;
foreach($content as $i => $content_id){
$q = $em->createQuery('update BRSPageBundle:Content c set c.display_order = ?1 where c.id = ?2')
->setParameter(1, $i)
->setParameter(2, $content_id);
$count += $q->execute();
}
return $count;
}
}然后假设您有一个内容ids数组,顺序如下:
$content = array(23,12,8,4);然后,您可以非常简单地从您的控制器更新订单:
$count = $this->getRepository('BRSPageBundle:Content')->reorder($content);https://stackoverflow.com/questions/8764029
复制相似问题