我正在尝试使用ajax更新实体,但它会添加一个新行来更新现有的。
我的实体:
关系:
类别 ManyToMany
产品
类别 OneToMany
子类别
类别实体
/**
* @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;
}
产品实体
/**
* @ORM\ManyToMany(targetEntity="Test\CoreBundle\Entity\Category", mappedBy="products" )
* @Exclude()
*/
protected $categories;
控制器
$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();
}
问题:
此代码将新产品添加到数据库,我想更新现有记录。
我尝试的事情:
persist
替换为merge
,没有任何区别。persist
,结果相同答案 0 :(得分:1)
我通过以下方式解决了问题:
1)我将persist
替换为merge
。
$em->merge($category);
$em->flush();
2)将级联选项从persist更改为merge
/**
* @ORM\ManyToMany(targetEntity="Test\CoreBundle\Entity\Product", inversedBy="categories", cascade={"merge"})
* @Groups({"public", "admin"})
*/
protected $products;