1
votes

I have some functionality that changes each element in collection of entity:

foreach ($screen->getBlocks() as $block) {
        $block->setSomeField();
}

After that I'm trying to persist object in database:

$this->em->persist($screen);
$this->em->flush();

The Screen::$blocks property has annotations:

/**
 * @ORM\OneToMany(targetEntity="App\Entity\Block", mappedBy="screen", cascade={"remove", "persist"}, orphanRemoval=true)
 * @ORM\OrderBy({"position": "ASC"})
 * @Groups({"block"})
 * @ApiSubresource
 * @Assert\Valid
 *
 * @var Block[]|Collection
 */
private $blocks;

Before flush I see that objects in collection are changed, but after - there values return back, seems that entityManager grabs if from database again. The only one solution that worked for me is adding $this->em->clear(); before flush, but I can't understand logic..

2

2 Answers

0
votes

Can you try moving the persist over the foreach loop like this:

$this->em->persist($screen);
foreach ($screen->getBlocks() as $block) {
    $block->setSomeField();
}
$this->em->flush();
0
votes

try following method and look different

dump($screen->getBlocks());
foreach ($screen->getBlocks() as $block) {
    $block->setSomeField();
    dump(block);
}
dump($screen->getBlocks());