【问题标题】:Doctrine entity relations not updated during same kernel request在同一内核请求期间未更新教义实体关系
【发布时间】:2021-04-11 17:16:27
【问题描述】:

我在学说中有两个实体对象:Product、ProductComponent。一个产品可以有多个组件。 首先创建 Product 实体,使用 EntityManager 进行持久化和刷新。 其次,创建产品组件,但不了解真实的产品对象,只知道产品的 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 时,返回的产品将具有组件关系。

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

【问题讨论】:

    标签: php doctrine-orm doctrine


    【解决方案1】:

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

    force the entity manager to update persisted entities,或者最好使用实体存储库获取所需的Product 实体:

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

    【讨论】:

    • 已经尝试过了,我已经用find 替换了getReference() 实现,但没有任何反应。引用的对象之前已经被持久化和刷新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-08
    • 2013-08-23
    • 2021-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多