9 / 11
タイトルの修正とか。

Doctrineで副問い合わせを使用したバルクUPDATE文について

Doctrine2でのバルクUPDATE文についてです。
QueryBuilder、および、DQLでは副問い合わせ利用した更新は出来ないという認識でいいのでしょうか。

以下のようなMySQLでは動くSQLをそのまま流し込んでいる処理があります。

https://github.com/sonata-project/SonataNewsBundle/blob/master/Entity/CommentManager.php#L70

$this->getConnection()->query(sprintf(
'UPDATE %s p, (SELECT c.post_id, count(*) as total FROM %s as c WHERE c.status = 1 GROUP BY c.post_id) as count_comment
SET p.comments_count = count_comment.total
WHERE p.id = count_comment.post_id'
, $postTableName, $commentTableName));

PostgreSQLでも動かしたいので、QueryBuilderで書き直してみようかと思い、以下のように書いてみました。

$qb = $this->getEntityManager()->createQueryBuilder();
$qb2 = $this->getEntityManager()->createQueryBuilder();
$qb2->select('c.post_id')
->addSelect($qb->expr()->count('*') .' as total')
->from($this->postManager->getClass(), 'c')
->where('c.status = 1')
->groupBy('c.post_id');

$qb->update($this->postManager->getClass(), 'p')
->set('p.commentsCount', 'count_comment.total')
->from($qb2, 'count_comment')
->where('news__post.id = count_comment.post_id');
$query = $qb->getQuery();
$query->execute();

しかし、以下のようなエラーが出ました。

[Doctrine\ORM\Query\QueryException]
  [Syntax Error] line 0, col 50: Error: Expected Doctrine\ORM\Query\Lexer::T_SET, got ','

[Doctrine\ORM\Query\QueryException]
UPDATE Application\Sonata\NewsBundle\Entity\Post p, SELECT c.post_id, COUNT(*) as total FROM Application\Sonata\NewsBundle\Entity\Post c WHERE c.status = 1 GROUP BY c.post_id count_comment SET p.commentsCount = count_comment.total WHERE news__post.id = count_comment.post_id

エラーで検索したのですが、以下のような記述がありました。
http://www.doctrine-project.org/jira/browse/DDC-1167

Doctrine DQL UPDATE does not allow to specify more than one table in an update statement, you have to use a subselect or rewrite this query otherwise.

subselectが何のことかよく分かりませんでした。

マニュアルには以下のようにあります。引用元:追加リンクを参照ください。

References to related entities are only possible in the WHERE clause and using sub-selects.

この文言のことをさしているのかと思うのですが、、、

引用元:追加リンク2
以下のようなDQLを想定しているようですので、今回の件とは違うようです。

createQuery('update UaePortailBundle:Note u set u.note = ?3
where IDNETITY(u.inscription) = ?1 and IDENTITY(u.elementmodule) = ?2 ');

QueryBuilder、および、DQLでは、副問い合わせを利用した更新は出来ないという認識でいいのでしょうか。
また、どのような書き換え方がありますでしょうか。