简体   繁体   English

在Symfony中使用学说更新实体

[英]Update Entity using Doctrine in Symfony

I want to update values in my Entity using PATCH method, but when I try to do that, doctrine create new record in table, but do not update. 我想使用PATCH方法更新实体中的值,但是当我尝试这样做时,原则会在表中创建新记录,但不更新。 For example I want to update name attribute, so I send this JSON array (in url I send id of the record: api.test/item/{id}): 例如,我想更新名称属性,因此我发送此JSON数组(在url中,我发送记录的ID:api.test / item / {id}):

{
   "name": "newname"
}

My Controller: 我的控制器:

public function updateItemAction(Request $request, $id)
{
    $serializer = $this->get('jms_serializer');

    $content = $request->getContent();

    $item = $serializer->deserialize($content,Item::class,'json');

    $em = $this->getDoctrine()->getManager();
    $em->getRepository(Item::class)->find($id);
    $em->persist($item);
    $em->flush();
    return new View("updated!",Response::HTTP_OK);
}

您必须从代码中撤回persist方法,它将更好地工作。

Have you tried using the merge() function? 您是否尝试过使用merge()函数? This allows you to merge the entity into the database, updating the existing entity. 这使您可以将实体合并到数据库中,从而更新现有实体。 Call this function instead of persist. 调用此函数而不是持久。 Here is a guide https://www.vivait.co.uk/labs/updating-entities-when-an-insert-has-a-duplicate-key-in-doctrine 这是指南https://www.vivait.co.uk/labs/updating-entities-when-an-insert-has-a-duplicate-key-in-doctrine

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM