我在持久化对象时遇到错误,说我需要在ManyToMany关系中配置cascade persist选项,但它已配置。
通过这种关系找到了一个新的实体&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);
}
窗体/类型/ 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'))
答案 0 :(得分:1)
在您的控制器中,尝试在刷新前添加$em->persist($image);
。
您的问题似乎是他无法创建shop_product_images_has_shop_products
表的值,因为图片还没有ID,因此您必须保留$image
和{{填充之前1}}实体。
此外,您的$product
应仅位于图片实体实体注释中,而不应位于产品实体注释中。
答案 1 :(得分:0)
在manyToMany上,你不需要cascade = {" persist"}
你有你的添加...()和删除...()它取代你的级联来将数据保存到中间表
在您的表单构建器中,您需要: - >添加(' ShopProductImages',' collection',array(' by_reference' => false,))
从注释中删除级联