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

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

问题描述

使用学说 symfony2 更新数据库中多条记录的最佳方法是什么?

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

我收到了我必须更新的记录 ID 数组.
我想将每个记录的索引从接收到的数组分配给列 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(n).

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

如何做得更好?

推荐答案

类似...

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

$em->flush();

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

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