Symfony - 更新多个记录 [英] Symfony - update multiple records

查看:94
本文介绍了Symfony - 更新多个记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用doctrine symfony2更新数据库中的多个记录的最佳方式是什么?

What is the best way to update multiple records in database using doctrine, symfony2?

我收到了我必须更新的记录数组。

我想将每个记录的索引从接收的数组分配给列show_order。
所以如果我收到数组$ array = array(22,1,5,10),那么我想做

I receive array of records ids which I have to update.
I want to assign to each record its index from received array to column show_order. So if i receive array $array = array(22, 1, 5, 10) then I want to do

 $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

but it's horrible way, because for each record I do one SELECT, so number of queries is O(n).

如何做得更好?

推荐答案

像$ ...

Something like...

foreach ($repo->findById($ids) as $obj) {
    $obj->setOrder(array_search($obj->getId(), $ids));
}

$em->flush();

这篇关于Symfony - 更新多个记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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