Reputation: 2599
I am trying to update entities using ajax but its adds a new row instead to update the existing one.
My entities:
Relations:
Category ManyToMany
Product
Category OneToMany
Subcategory
Category Entity
/**
* @ORM\ManyToMany(targetEntity="Test\CoreBundle\Entity\Product", inversedBy="categories", cascade={"persist"})
* @Groups({"public", "admin"})
*/
protected $products;
public function setProducts( $products) {
$this->products= new ArrayCollection($products->toArray());
return $this;
}
Product Entity
/**
* @ORM\ManyToMany(targetEntity="Test\CoreBundle\Entity\Category", mappedBy="products" )
* @Exclude()
*/
protected $categories;
Controller
$toSave = $this->get('request')->getContent();
$s = $serializer->deserialize($toSave, Test\CoreBundle\Entity\Category, 'json');
if ($s->getId() > 0) {
$category= $em->getRepository('TestCoreBundle:Category)->findOneBy(['id' => $s->getId()]);
$category->setName($s->getName());
$category->setIsDisabled($s->getIsDisabled());
$category->setIsPrivate($s->getIsPrivate());
$category->setQuestions($s->getCategories());
$em->persist($category);
$em->flush();
}
Problem:
This code adds new products to database, I want to update the existing records.
Things I tried:
persist
with merge
, made no difference.persist
, same resultUpvotes: 0
Views: 146
Reputation: 2599
I solved the problem the following way:
1) I replaced persist
with merge
.
$em->merge($category);
$em->flush();
2) Changed the cascade option from persist to merge
/**
* @ORM\ManyToMany(targetEntity="Test\CoreBundle\Entity\Product", inversedBy="categories", cascade={"merge"})
* @Groups({"public", "admin"})
*/
protected $products;
Upvotes: 1