php - 在同一内核请求期间未更新教义实体关系
问题描述
我在学说中有两个实体对象: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();
推荐阅读
- java - 没有代理的 RestTemplate 调用
- ios - 带有子视图的 MapKit 地图不会添加注释
- java - 将 onClick 添加到 RecyclerView 项目的一部分
- python - 根据来自其他数据框的关系创建新的数据框
- python - 可能存在重复浮点数时对单个(均匀随机)浮点值的 SQL 查询
- c# - 为什么 Chrome 驱动程序在作为 NUnit 项目时没有打开,但在添加了 Nuget 包的控制台应用程序中工作正常?
- javascript - 括号表示法是用引号访问对象
- flask - 使用原始 sqlalchemy 时删除每个请求的会话
- php - 几个模拟连接对数据库的影响
- karma-jasmine - 如何模拟 this.route.queryParams.subscribe