Search code examples
doctrinedql

Doctrine where condition for many to one


I have a many to one association mapping where many Exams have one subject If I have to update marks property of all subject with exam id xxxx I use

Update namespace/Exam e set e.marks = 4 where e.subject.id = xxxx

it is not working can you please he help me to do that in a proper way ?


Solution

  • You can not access e.subject.id without a join in your query. But a join is not possible in a Doctrine update statement, since its MySQL specific.

    What should work is to compare the whole entity:

    $subject = $this->getEntityManager()->getRepository('namespace\subject')
        ->find(xxx);
    
    $query = $this->getEntityManager()->createQueryBuilder()
        ->update('namespace\Exam', 'e') 
        ->set('e.marks', '4')
        ->where('e.subject = :subject')
        ->setParameter('subject', $subject);
    

    Or, if you don't want to have another database query and the primary key of your subject entity consists only of one column (e.g. id), you could also compare with this primary key:

    $query = $this->getEntityManager()->createQueryBuilder()
        ->update('namespace\Exam', 'e') 
        ->set('e.marks', '4')
        ->where('e.subject = :id')
        ->setParameter('id', xxx);
    

    Also have a look at this question, the user wasn't able to join in his update statement too.

    Edit: added more general approach