i.am.michiel
i.am.michiel

Reputation: 10404

Why is doctrine updating every single object of my form?

I've got a big Symfony 2 form on a huge collection (over 10k objects). For simple reasons, I cannot display a form of thousands of objects. I am displaying a form of about 300 objects.

I have found no way to filter a collection into a form and thus do the following :

    $bigSetOfObjects = array(
        'myObject' => $this
                ->getDoctrine()
                ->getRepository('MyObject')
                ->findBy(... )
    );

    $form = $this->createForm(new MyObjectForm(), $bigSetOfObjects);

    // And a little further
    if ($this->getRequest()->getMethod() == 'POST') {
        $form->bindRequest($this->getRequest());
        $this->getDoctrine()->getEntityManager()->flush();
    }           

Everything works great. Form is displayed with the correct values and the update works fine also. Data is correctly saved to the database. The problem is that Doctrine is executing a single update statement per object meaning the whole page is about 300 SQL statements big causing performance issues.

What I do not understand is that I'm updating only a couple of values of the form, not all of them. So why is Doctrine not able to detect the updated objects and thus update only those objects in the database?

Is there anything I'm doing wrong? I might have forgotten?

Upvotes: 5

Views: 584

Answers (1)

MDrollette
MDrollette

Reputation: 6927

By default Doctrine will detect changes to your managed objects on a property-by-property basis. If no properties have changed then it should not be executing an update query for it. You may want to check that the form isn't inadvertently changing anything.

You can, however, change how doctrine determines that an object has changed by modifying the tracking policy. Since you are working with a lot of objects you may want to change to the DEFERRED_EXPLICIT tracking policy. With this method you would specifically call:

$em->persist($object);

on the entities that you want to be updated. You would have to implement your own logic for determining if an object needs to be persisted.

Upvotes: 8

Related Questions