条令实体关系在同一内核请求期间未更新



我在条令中有两个实体对象: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时,返回的产品将具有组件关系。

这是什么原因?有什么东西不见了吗?

这是因为您使用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();

最新更新