W
W
wwspb2017-04-27 11:21:04
symfony
wwspb, 2017-04-27 11:21:04

How to properly work with PersistentCollection in Doctrine ORM?

There are two entities A and B, a many-to-one relationship.
I create entity A, add some B entities to it. Now A contains a PersistentCollection object, but it is empty until I flush(). Is it normal that at this stage I cannot work fully with the relationship between entities until I put them in the database?
Everything looks like this:

$entityA = $entity_manager->getRepository(...)->find(1);
foreach (...) {
    $entityB = new EntityB();
    $entityB->setEntityA($entityA);

    $entityA->addEntitiesB($entityB);

    $entity_manager->persist($entityB);
}

// теперь если здесь не выполнить $entity_manager->flush()
// то $entitiesB будет содержать пустой объект PersistentCollection
$entitiesB = $entityA->getEntitiesB();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Pavlov, 2017-04-27
@lexxpavlov

This most likely happens if you take $entityA->getEntitiesB(); in the second case. on another object obtained from the repository.

$entityA1 = $entity_manager->getRepository(...)->find(1);
$entityA1->addEntitiesB(new EntityB());

$entityA2 = $entity_manager->getRepository(...)->find(1); // получаем новый объект (из базы)
$entitiesB = $entityA2->getEntitiesB(); // пусто
$entitiesB = $entityA1->getEntitiesB(); // а тут будет сохранённый объект

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question