Doctrine flush不会更新相关的集合实体

时间:2018-05-31 12:44:08

标签: symfony doctrine-orm symfony4

我有一些功能可以更改实体集合中的每个元素:

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

之后我试图在数据库中保留对象:

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

Screen :: $ blocks属性有注释:

/**
 * @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;

在刷新之前,我看到集合中的对象被更改了,但之后 - 返回值,似乎entityManager再次从数据库中获取。对我有用的唯一解决方案是在刷新之前添加 $ this-> em-> clear(); ,但我无法理解逻辑..

2 个答案:

答案 0 :(得分:0)

你能尝试将持久性移动到foreach循环上,如下所示:

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

答案 1 :(得分:0)

尝试以下方法,看起来与众不同

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