【发布时间】:2018-04-25 13:47:25
【问题描述】:
我在持久化对象时出错,说我需要在多对多关系中配置级联持久化选项,但它已配置。
通过关系“AppBundle\Entity\ShopProducts#shopProductImages”找到了一个新实体,该实体未配置为对实体进行级联持久化操作:AppBundle\Entity\ShopProductImages@000000007d4db89e00000000344e8db2。要解决此问题:在此未知实体上显式调用 EntityManager#persist() 或配置级联在映射中保持此关联,例如 @ManyToOne(..,cascade={"persist"})。如果您无法找出导致问题的实体,请执行 'AppBundle\Entity\ShopProductImages#__toString()' 以获得线索。
$product = new ShopProducts();
$form = $this->createForm(ProductTypeNew::class, $product);
if ($form->isSubmitted() && $form->isValid())
{
$image = new ShopProductImages();
...
$product->addShopProductImages($image);
...
$em->persist($product);
$em->flush();
实体/ShopProducts.php
/**
* @var \Doctrine\Common\Collections\Collection
*
* @ORM\ManyToMany(
* targetEntity="AppBundle\Entity\ShopProductImages",
* mappedBy="shopProducts",
* cascade={"persist"}
* )
*/
private $shopProductImages;
/**
* @return ArrayCollection|ShopProductImages[]
*/
public function getShopProductImages()
{
return $this->shopProductImages;
}
public function addShopProductImages(ShopProductImages $image)
{
if ($this->shopProductImages->contains($image)) {
return;
}
$this->shopProductImages[] = $image;
$image->addImagesProduct($this);
}
public function removeShopProductImages(ShopProductImages $image)
{
if (!$this->shopProductImages->contains($image)) {
return;
}
$this->shopProductImages->removeElement($image);
$image->removeImagesProduct($this);
}
实体/ShopProductImages.php
/**
* @var \Doctrine\Common\Collections\Collection
*
* @ORM\ManyToMany(targetEntity="AppBundle\Entity\ShopProducts",
* inversedBy="shopProductImages",
* cascade={"persist"}
* )
* @ORM\JoinTable(name="shop_product_images_has_shop_products"),
* joinColumns={
* @ORM\JoinColumn(name="shop_product_images_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* @ORM\JoinColumn(name="shop_products_id", referencedColumnName="id")
* }
*/
private $shopProducts;
public function addImagesProduct(ShopProducts $product)
{
if ($this->shopProducts->contains($product)) {
return;
}
$this->shopProducts[] = $product;
$product->addShopProductImages($this);
}
public function removeImagesProduct(ShopProducts $product)
{
if (!$this->shopProducts->contains($product)) {
return;
}
$this->shopProducts->removeElement($product);
$product->removeShopProductImages($this);
}
Form/Type/ProductTypeNew.php
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('price')
->add('description', TextareaType::class)
->add('quantity')
->add('file', FileType::class, array('label' => 'Zdjęcie'))
【问题讨论】:
-
你试过添加 $shopProductImages = New.... (...) $em->persist($shopProductImages);在你的控制器中
-
是的,这是在主帖中。
-
我说的是 $em->persist($shopProductImages),而不是 $product。但如果它有效,我认为这是一个不好的做法。
-
是的,我试过了,它将数据保存到两个表,但不保存到中间表。
-
我认为你的分析器在这里:afilina.com/doctrine-not-saving-manytomany