Symfony3 - 在单个sql查询中更新多个实体

Loï*_*men 1 php symfony

这个旧帖子反弹我正在寻找一种方法来更新一个SQL查询中的几个Symfony entites - 出于优化原因.我有一个Content实体,以及一个服务中的方法,它使用setCurrent(0)更新所有"兄弟"内容.到目前为止,这是工作代码:

/**
 * Set given content the latest regarding its siblings
 */
public function setLatestContent(Entity\Content $content)
{
    // Get siblings entities
    $siblings = $this
        ->em
        ->getRepository('LPFrontRteBundle:Content')
        ->findBySibling($content);

    foreach ($siblings as $sibling_content) {
        $sibling_content->setCurrent(0);
    }

    $this->em->flush();
}
Run Code Online (Sandbox Code Playgroud)

那很有效.但由于我有38个兄弟内容,我得到38个SQL查询,如:

UPDATE mr_content SET current = 0 WHERE id = 55
UPDATE mr_content SET current = 0 WHERE id = 56
UPDATE mr_content SET current = 0 WHERE id = 57
...
Run Code Online (Sandbox Code Playgroud)

我想使用Doctrine的"干净"实体系统,以某种方式获得一个查询:

UPDATE mr_content SET current = 0 WHERE id = 55 OR id = 56 OR id = 57 ...
Run Code Online (Sandbox Code Playgroud)

任何关于如何实现这一点的想法 - 或更聪明的解决方法,将不胜感激.


编辑

为了记录,这是我想出的 - 我喜欢它详细:)使用$ qb作为查询构建器.

    $qb->update('LPFrontRteBundle:Content', 'c')
        ->set('c.current', 0)

        ->where('c.keyword = :keyword')
        ->setParameter('keyword', $content->getKeyword())

        ->andWhere('c.locale = :locale')
        ->setParameter('locale', $content->getLocale())

        ->andWhere('c.id != :id')
        ->setParameter('id', $content->getId())

        ->getQuery()->execute();
Run Code Online (Sandbox Code Playgroud)

Jak*_*zak 5

批量处理是您正在寻找的.

Doctrine2中有两种批量更新方法.

第一个是DQL更新查询,最适合您.它会是这样的:

$q = $em->createQuery("UPDATE LPFrontRteBundle:Content c SET c.current = 0 WHERE id IN (:ids)")
        ->setParameter(':ids', $ids, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY));
$numUpdated = $q->execute();
Run Code Online (Sandbox Code Playgroud)