簡體   English   中英

Symfony 4 更新具有關系的學說實體

[英]Symfony 4 update doctrine entity with relationships

我在更新應用程序中的 Doctrine 實體時遇到問題。

這是我的代碼

public function put(Request $request, $id)
{
    $data = json_decode($request->getContent(), true);

    /** @var Product $entity */
    $entity = $this->findOneById($id);

    $this->denyAccessUnlessGranted(BaseVoter::EDIT, $entity);

    $form = $this->createForm($this->formType, $entity);

    $form->submit($data);

    if (false === $form->isValid()) {
        return new JsonResponse(
            [
                'status' => 'error',
                'errors' => $this->formErrorSerializer->convertFormToArray($form),
            ],
            JsonResponse::HTTP_BAD_REQUEST
        );
    }

    /** @var Product $product */
    $product = $form->getData();
    $this->entityManager->persist($product);
}

我的問題來自表單處理數據提交的方式。 一旦我運行$form->submit()方法,我的持久化實體也會更新,因此我只有新值並且無法取消我的舊關系。

由於實體在submit過程中似乎已經被持久化(以一種隱藏的方式),即使我嘗試從 Doctrine 再次獲取它,我仍然只獲得新值。

有什么好的方法嗎?

我不知道你為什么要使用表單組件來做到這一點。 這是一個更符合 API 精神的替代方案,讓您可以更好地控制正在發生的事情:

public function put(Request $request, $id)
{
    $data = json_decode(
        $request->getContent(),
        true
    );

    /** @var Product $entity */
    $entity = $this->findOneById($id);
    if (null === $entity) {
        throw new NotFoundHttpException();
    }

    $this->denyAccessUnlessGranted(BaseVoter::EDIT, $entity);

    foreach ($data as $property => $value) {
        try {
            $this->propertyAccessor->setValue($entity, $property, $value);
        } catch (\Exception $e) {
            // Handle bad property name, etc..
        }
    }

    $constraintsViolations = $this->validator->validate($entity);
    if (count($constraintsViolations) > 0) {
        return new JsonResponse(
            [
                'status' => 'error',
                'errors' => $constraintsViolations,
            ],
            JsonResponse::HTTP_BAD_REQUEST
        );
    }

    $this->entityManager->persist($entity);
    $this->entityManager->flush();

    return new JsonResponse(...);
}

在這里,我使用了表單組件本身在引擎蓋下使用的 2 個其他組件:

  • 帶有Symfony\\Component\\PropertyAccess\\PropertyAccessorInterface 的屬性訪問器
  • 帶有Symfony\\Component\\Validator\\Validator\\ValidatorInterface 的驗證器

您必須從控制器構造函數中注入它。

我希望它會幫助你!

此示例也不完整,您必須改進錯誤處理和響應。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM