Entity Manger only persisting one Entity at a time #5218

Closed
opened 2026-01-22 15:01:48 +01:00 by admin · 4 comments
Owner

Originally created by @eggmatters on GitHub (Aug 16, 2016).

I am writing a series of unit tests on a service. I need entities in various states for different test cases.
I have written methods which accept arrays of values, populates an entity with some values. The first test case that calls these methods operates fine. Subsequent calls fail however with the error:

Undefined index: <some hash value>

The test cases are structured thusly:

class someTest extends WebTestCase {

  public funtion testOne() {
     $entityArray = ['valOne' => 1, 'valTwo' => 2];
     $entity = $this->fetchEntity($entityArray);
     //make assetions etc.
  }

  public function testTwo() {
     $entityArray = ['valOne' => 2, 'valTwo' => 3];
     //Fails with Undefined index when flush() is called from method:
     $entity = $this->fetchEntity($entityArray);
  }
  private function fetchEntity($entityArray) {
    $container = $this->createClient()->getContainer();
    $em = $container->get('doctrine')->getManager();
    $myEntity = new MyEntity();
    $myEntity->setValOne($entityArray['valOne']);
    $myEntity->setValTwo($entityArray['valTwo']);
    $em->persist($myEntity);
    $em->flush(); //'Undefined index' Error thrown from here only on second call.
    return $myEntity();
  }

Expected: Calls to fetchEntity with valid values will persist entity and return persisted entity.
Actual: 'Undefined Index ' is thrown when calling $em->flush().

Stack trace shown is:

1) tests\AppBundle\Services\Response\someTest::someTest
Undefined index: 000000006994fd4c0000000020e08b96

. . . /vendor/symfony/phpunit-bridge/DeprecationErrorHandler.php:72
. . . /vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:2917
. . . /vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/Entity/BasicEntityPersister.php:656
. . . /vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/Entity/BasicEntityPersister.php:692
. . . /vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/Entity/BasicEntityPersister.php:271
. . . /vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:1018
. . . /vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:378
. . . /vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php:356
. . . /tests/AppBundle/Services/Response/someTest.php:231 (line where flush() is called.)
. . . /tests/AppBundle/Services/Response/someTest.php:104
Originally created by @eggmatters on GitHub (Aug 16, 2016). I am writing a series of unit tests on a service. I need entities in various states for different test cases. I have written methods which accept arrays of values, populates an entity with some values. The first test case that calls these methods operates fine. Subsequent calls fail however with the error: `Undefined index: <some hash value>` The test cases are structured thusly: ``` php class someTest extends WebTestCase { public funtion testOne() { $entityArray = ['valOne' => 1, 'valTwo' => 2]; $entity = $this->fetchEntity($entityArray); //make assetions etc. } public function testTwo() { $entityArray = ['valOne' => 2, 'valTwo' => 3]; //Fails with Undefined index when flush() is called from method: $entity = $this->fetchEntity($entityArray); } private function fetchEntity($entityArray) { $container = $this->createClient()->getContainer(); $em = $container->get('doctrine')->getManager(); $myEntity = new MyEntity(); $myEntity->setValOne($entityArray['valOne']); $myEntity->setValTwo($entityArray['valTwo']); $em->persist($myEntity); $em->flush(); //'Undefined index' Error thrown from here only on second call. return $myEntity(); } ``` Expected: Calls to fetchEntity with valid values will persist entity and return persisted entity. Actual: 'Undefined Index <some hash value>' is thrown when calling $em->flush(). Stack trace shown is: ``` php 1) tests\AppBundle\Services\Response\someTest::someTest Undefined index: 000000006994fd4c0000000020e08b96 . . . /vendor/symfony/phpunit-bridge/DeprecationErrorHandler.php:72 . . . /vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:2917 . . . /vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/Entity/BasicEntityPersister.php:656 . . . /vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/Entity/BasicEntityPersister.php:692 . . . /vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/Entity/BasicEntityPersister.php:271 . . . /vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:1018 . . . /vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:378 . . . /vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php:356 . . . /tests/AppBundle/Services/Response/someTest.php:231 (line where flush() is called.) . . . /tests/AppBundle/Services/Response/someTest.php:104 ```
admin closed this issue 2026-01-22 15:01:48 +01:00
Author
Owner

@eggmatters commented on GitHub (Aug 17, 2016):

File this one under "good to know";
Unsure of underlying cause but it when I migrated the factory methods to generate entities to a class which provided it's own EM and container, the entities persisted. One could draw an assumption that the entity manager is a separate instance when called. This seems to confuse things when persisting however.

When inspecting the failure in UnitOfWork.php:2917, A method is looking for an entry in an array keyed by the value from above array( '000000006994fd4c0000000020e08b96' => 'id' => <some guid>) There was an entry in the entities array for that id, mapping to the guid I needed but was throwing the 'undefined index' error. Not sure what the function of that array may be.

@eggmatters commented on GitHub (Aug 17, 2016): File this one under "good to know"; Unsure of underlying cause but it when I migrated the factory methods to generate entities to a class which provided it's own EM and container, the entities persisted. One could draw an assumption that the entity manager is a separate instance when called. This seems to confuse things when persisting however. When inspecting the failure in `UnitOfWork.php:2917`, A method is looking for an entry in an array keyed by the value from above `array( '000000006994fd4c0000000020e08b96' => 'id' => <some guid>)` There was an entry in the entities array for that id, mapping to the guid I needed but was throwing the 'undefined index' error. Not sure what the function of that array may be.
Author
Owner

@eggmatters commented on GitHub (Aug 19, 2016):

As a follow up, I've noticed a pattern with this and errors like it. It seems that if you invoke an entity manager to either fetch or generate an Entity and then invoke a new entity manager to persist that entity, you have problems.

In the code above, an EntityManager was invoked to create the object - and a different EM was invoked to persist it. Entity managers should, I guess, be in lockstep with the entities they manage.

@eggmatters commented on GitHub (Aug 19, 2016): As a follow up, I've noticed a pattern with this and errors like it. It seems that if you invoke an entity manager to either fetch or generate an Entity and then invoke a new entity manager to persist that entity, you have problems. In the code above, an EntityManager was invoked to create the object - and a different EM was invoked to persist it. Entity managers should, I guess, be in lockstep with the entities they manage.
Author
Owner

@Skemeth commented on GitHub (Mar 22, 2018):

I'm having the same problem today. here's a short version of my code:

    public function execute(AMQPMessage $msg)
    {
        $params = unserialize($msg->body);

        $em = $this->em;
        $em->getConnection()->getConfiguration()->setSQLLogger(null);

        if (null != $params['post'] && $params['post'] != '') {
            $post = $em->getRepository('Post')->findOneBy(['id' => $params['post']]);

            $query = $em->createQueryBuilder();
            $query->select('n')
                ->from('Message', 'n')
                ->join('n.post', 'p')
                ->andWhere('p.id = :postId')
                ->setParameter('postId', $params['post'])
                ->orderBy('n.creationDate', 'desc');
            $message = $query->getQuery()->getFirstResult();

            if (!$message) { // Creation of a new message
                $message = new Message();
                $message->setTitle("My awesome title");
                $message->setText('My awesome message');
                $message->setPost($post);

            } else { // changing message
                $message->setMessage('my Super Mega Awesome message!');
            }
            $em->persist($message);
            $em->flush();
        }
    }

The problem happens when the message is not found (second "if" test)
I believe I used the same entity manager to create and persist, so I have no idea how to fix this...?

@Skemeth commented on GitHub (Mar 22, 2018): I'm having the same problem today. here's a short version of my code: ```php public function execute(AMQPMessage $msg) { $params = unserialize($msg->body); $em = $this->em; $em->getConnection()->getConfiguration()->setSQLLogger(null); if (null != $params['post'] && $params['post'] != '') { $post = $em->getRepository('Post')->findOneBy(['id' => $params['post']]); $query = $em->createQueryBuilder(); $query->select('n') ->from('Message', 'n') ->join('n.post', 'p') ->andWhere('p.id = :postId') ->setParameter('postId', $params['post']) ->orderBy('n.creationDate', 'desc'); $message = $query->getQuery()->getFirstResult(); if (!$message) { // Creation of a new message $message = new Message(); $message->setTitle("My awesome title"); $message->setText('My awesome message'); $message->setPost($post); } else { // changing message $message->setMessage('my Super Mega Awesome message!'); } $em->persist($message); $em->flush(); } } ``` The problem happens when the message is not found (second "if" test) I believe I used the same entity manager to create and persist, so I have no idea how to fix this...?
Author
Owner

@Ocramius commented on GitHub (Mar 22, 2018):

Not an ORM issue: please report it here after reproducing in isolation in https://github.com/doctrine/doctrine2/tree/master/tests/Doctrine/Tests/ORM/Functional/Ticket, not with your specific app.

@Ocramius commented on GitHub (Mar 22, 2018): Not an ORM issue: please report it here after reproducing in isolation in https://github.com/doctrine/doctrine2/tree/master/tests/Doctrine/Tests/ORM/Functional/Ticket, not with your specific app.
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: doctrine/archived-orm#5218