通过关系发现了一个新的实体——学说

A new entity was found through the relationship - Doctrine

我有一个缓存的实体产品。我检索实体并更新一些属性,包括向其中添加价格。

关系是这样设置的

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();

但每当我这样做时,我都会收到异常消息。

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();

它没有抛出任何错误,但没有数据保存在数据库中。也不确定这个问题是否相关。

我也尝试过级联,但它给出了不同的错误。有什么办法可以解决这个问题。

据我了解,Doctrine 实体管理器相当擅长(至少,人们希望如此)管理其结果缓存,因此直接摆弄它可能是个问题。

与其直接访问结果缓存,不如尝试使用:

$product = $entityManager->find('Product',$key);

然后,您似乎在最后一行也有错字 - 在 "entityManager" 中缺少 "e" - 但我确信这会引发错误,所以它可能是 copy/paste 创建此问题时出现问题。

编辑: 您同时使用了 $product$productEntity。如果这些是同一个变量,您应该选择一个名称并坚持使用它。

@Rushing 非常感谢您的回复。你是对的,有一些拼写错误,因为我必须对代码进行一些更改才能粘贴到 Whosebug 中,但实际代码是正确的。很抱歉我回复这个话题有点晚了。您提供的解决方案很好,但更好的解决方案是像这样使用合并。

$productEntity = $em->merge($productEntity);
....rest of the logic

这样我们就不用再去查询数据库了,实体是新鲜的。