2

Currently, this is the way, how I update a selected row, through find & update.

private function turnOnLight($entity_manager, $model, $year)
{
    // Is this an optimized way to update a single column? 
    // It seems not as we need 2 rounds DB communication trip.

    $car = $entity_manager->findOneBy(array(
        'model' => $model,
        'year'  => $year,
        'light' => 0
    ));

    if (is_null($car)) {
        return;
    }

    $car->light = 1;
    $entity_manager->persist($car);
    $entity_manager->flush();
}

However, I don't feel this is efficient enough, as it requires 2 DB operations (find & update).

Is there any way to optimize the above code?

Cheok Yan Cheng
  • 47,586
  • 132
  • 466
  • 875
  • 1
    You will find your answer here: http://stackoverflow.com/questions/4337751/doctrine-2-update-query-with-query-builder – colburton Jun 24 '14 at 14:41
  • It does feel right to me, you need to pull the entity from the database then update it, if it exists which let you have a specific behaviour when the entity is not found. In *"a doctrine way"* I don't think this code can be optimized. You can still if you need, process [an update query](http://docs.doctrine-project.org/en/2.1/reference/dql-doctrine-query-language.html#update-queries) straight with your conditions – Touki Jun 24 '14 at 14:55

1 Answers1

0

As people have mentioned in the comments, this is correct.

If you don't have the reference to the object the first thing to do is retrieve this.

It may be even better to split this into two since if something happends when retrieving it's easier to debug or to fix this.

One small tip, when updating an already existing entity, by already existing I mean something that is in the database, you should not call call $entity_manager->persist($car).

The persist method lets Doctrine know that it should keep track of this entity, however because it's already in the database Doctrine knows about it so it will update it automatically when any of the properties change.

To make a long story short, calling flush is enough.

JKaan
  • 359
  • 2
  • 14