Doctrine Query Builder not working with UPDATE and INNER JOIN

大憨熊 提交于 2019-12-18 05:55:51

问题


In my repository I have this query:

$qb = $this->getEntityManager()->createQueryBuilder();
$qb
    ->update('MyBundle:Entity1', 'e1') 
    ->join('e1.Entity2', 'e2')
    ->set('e1.visibile', '1')
    ->andWhere('e2.id = :id')->setParameter("id", 123)
;

throw this error

[Semantical Error] line 0, col 66 near 'e2.id = :id': Error: 'e2' is not defined

I have checked the relation and it is right. Is there any issue using join in query update?


回答1:


You can not use join on update and delete queries. You have to use subqueries.

Joins are not supported on update and delete queries because it is not supported on all dbms. It won't be implemented in Doctrine 1 or Doctrine 2. You can however get the same affect by using subqueries.

http://www.doctrine-project.org/jira/browse/DC-646

If you are using MySQL, using subqueries will not work. You will have then to use 2 queries.

In MySQL, you cannot modify a table and select from the same table in a subquery

http://dev.mysql.com/doc/refman/5.0/en/subqueries.html




回答2:


Doctrine DQL does not support join in update.

Try doing the following :

$qb = $this->getEntityManager()->createQueryBuilder();
$qb
    ->update('MyBundle:Entity1', 'e1') 
    ->set('e1.visibile', '1')
    ->where('e1.Entity2 = :id')
    ->setParameter("id", 123)
;

You can set the id, as long as it is the primary key, of the linked entity directly as if it was the entity, Doctrine will map it.

I'm doing the exact same thing in my queries and it works.




回答3:


try using a subquery instead Join will not work in DQL while you re doing an update:

LEFT JOIN, or JOINs in particular are only supported in UPDATE statements of MySQL. DQL abstracts a subset of common ansi sql, so this is not possible. Try with a subselect:

$qb = $this->getEntityManager()->createQueryBuilder();
    $qb ->update('MyBundle:Entity1', 'e') 
        ->set('e.visibile', '1')
        ->where('e.id IN (SELECT e1.id FROM Entity1 e1 INNER JOIN e2.Entity2 e2 WHERE e2 = :id')
        ->setParameter("id", 123);


来源:https://stackoverflow.com/questions/15293502/doctrine-query-builder-not-working-with-update-and-inner-join

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!