Search code examples
phpdoctrine-ormsql-updatedql

How to update field based on another field in table in Doctrine2?


I have table with two columns: price and constant.

I would like to run update on all entries in table to update price based on constant * coefficient.

How could I do such query?


Solution

  • You can do that with a DQL query:

    $em->createQuery('
        UPDATE entityClass e
        SET e.price = e.constant * 33;
    ');
    

    You can also do that with raw SQL:

    $em->getConnection()->executeUpdate('
        UPDATE entity_table_name AS e
        SET e.price = e.constant * 33;
    ');
    

    You could also add a listener on the preUpdate & prePersist doctrine event, so that these values are updated automatically.

    See http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#preupdate for an example.

    So that each time you save your entity, it will update the related field automatically.