Doctrine orm 通过关系主义找到了一个新的实体
我有一个缓存的实体产品。我检索实体并更新一些属性,包括向其中添加价格 关系是这样建立起来的Doctrine orm 通过关系主义找到了一个新的实体,doctrine-orm,entity,Doctrine Orm,Entity,我有一个缓存的实体产品。我检索实体并更新一些属性,包括向其中添加价格 关系是这样建立起来的 class Product { /** * @var ArrayCollection * * @ORM\OneToMany(targetEntity="Price", mappedBy="product", fetch="EXTRA_LAZY") */ private $prices; } class Price { /** *
class Product
{
/**
* @var ArrayCollection
*
* @ORM\OneToMany(targetEntity="Price", mappedBy="product", fetch="EXTRA_LAZY")
*/
private $prices;
}
class Price
{
/**
* @var Product
*
* @ORM\ManyToOne(targetEntity="Product", inversedBy="prices")
* @ORM\JoinColumn(name="product_id", referencedColumnName="id")
*/
private $product;
}
我正试图保存这样的属性
// Here $em is Entity Manager
$cacheDriver = $em->getConfiguration()->getResultCacheImpl();
$product = $cacheDriver->fetch($key)
$product->setUpdatedAt(new \DateTime());
$price = new Price;
$label = $em->getReference(PriceLabelEntity::class, $labelId);
$price->setLabel($label)
->setPriceLabelId($labelId)
->setProduct($productEntity)
->setProductId($product->getId());
$em->persist($price);
$product->addPrice($price);
$em->flush();
$productEntity = $em->merge($productEntity);
....rest of the logic
但每当我这么做的时候,我都会听到一句例外的话
A new entity was found through the relationship 'Price#product' that was not
configured to cascade persist operations for entity:
Product@0000000043c0cdc400007fec6b41ca76. To solve this issue: Either
explicitly call EntityManager#persist() on this unknown entity or configure
cascade persist this association in the mapping for example
@ManyToOne(..,cascade={"persist"}). If you cannot find out which entity
causes the problem implement 'Product#__toString()' to get a clue.
如果我只是这样做,更奇怪的问题
$product->setUpdatedAt($timeStamp);
$em->flush();
它不会抛出任何错误,但数据库中不会保存任何数据。也不确定这些问题是否相关
我也试着把cascade放进去,但它给出了不同的错误。有什么办法可以解决这个问题。据我所知,条令实体经理在管理其结果缓存方面相当熟练(至少有人希望如此),因此直接处理它可能是个问题 不要直接命中结果缓存,请尝试使用:
product=$entityManager->find('product',$key)代码>
然后,您似乎在最后一行有一个输入错误-在“entityManager”中缺少一个“e”-但我确信这会抛出一个错误,因此在创建此问题时可能是复制/粘贴问题
编辑:您还同时使用了$product
和$productEntity
。如果这些变量是同一个变量,您应该选择一个名称并坚持使用。@Rushing非常感谢您的回复。你是对的,有一些拼写错误,因为我必须在代码中做一些更改才能粘贴到StackOverflow中,但实际的代码是正确的。很抱歉,我在回答这个问题时有点晚了。您提供的解决方案很好,但更好的解决方案是像这样使用merge
// Here $em is Entity Manager
$cacheDriver = $em->getConfiguration()->getResultCacheImpl();
$product = $cacheDriver->fetch($key)
$product->setUpdatedAt(new \DateTime());
$price = new Price;
$label = $em->getReference(PriceLabelEntity::class, $labelId);
$price->setLabel($label)
->setPriceLabelId($labelId)
->setProduct($productEntity)
->setProductId($product->getId());
$em->persist($price);
$product->addPrice($price);
$em->flush();
$productEntity = $em->merge($productEntity);
....rest of the logic
通过这种方式,我们不必再次查询数据库,实体是新的