首页 > 解决方案 > 在同一内核请求期间未更新教义实体关系

问题描述

我在学说中有两个实体对象:Product、ProductComponent。一个产品可以有多个组件。首先创建 Product 实体,使用 EntityManager 进行持久化和刷新。其次,创建产品组件,但不了解真正的 Product 对象,只知道产品的 id:

<?php
// run kernel..

// Product was persisted before in another class, during same kernel request

$em = ...

$productId = 'some-uuid';

$productReference = $em->getReference(Product::class, $productId);

$productComponent = new ProductComponent();
$productComponent->setProduct($productReference);

$em->persist($productComponent);
$em->flush();

$productRepository = $em->getRepository(Product::class);
$product = $productRepository->find($productId);

$components = $product->getProductComponents();
// $components will be empty ArrayCollection

// but what works:
$componentRepository = $em->getRepository(ProductComponent::class);
$components = $componentRepository->findBy(['product' => $productId]);

// $components will be found with the provided $productId

// end kernel..

当我现在$productRepository从新的内核请求访问时,返回的产品将具有组件关系。

这是什么原因?有什么遗漏吗?

标签: phpdoctrine-ormdoctrine

解决方案


这是因为您使用EntityManagerInterface::getReference的是分配代理 Product实体ProductComponent而不是持久Product实体。实际持久化(在内存中)Product实体然后不会更新以将新添加的实体ProductComponent作为其集合的一部分(导致$product->getProductComponents()为空)。

要么强制实体管理器更新持久化实体,要么最好使用实体存储库获取所需的实体:Product

<?php
//...
$productRepository = $em->getRepository(Product::class);
$product = $productRepository->find($productId);
$productComponent->setProduct($product);
$em->persist($productComponent);
$em->flush();

推荐阅读