从学说中的集合中删除项目

removing items from a collection in doctrine

我正在使用 Symfony 3.x 和 Doctrine。我有一个集合实体 quoteItemAdditionalWork,它与 QuoteItem 实体关联。我有另一个名为 WorkOrder 的实体。 WorkOrder 实体是表单 WorkOrderType 的指定 data_class。在 WorkOrderType 表单上,我需要将来自 QuoteItem 实体的表单元素包含为未映射的表单字段(一个 data_class 每个表单类型 -symfony 规则)。表单集合 quoteItemAdditionalWork 是 WorkOrderType 表单中包含的表单字段之一,并且在表单上未映射,因为 quoteItemAdditionalWork 与 WorkOrder 没有实体关联。

public function buildForm (FormBuilderInterface $builder, array $options)
{
    $builder->add('quoteItemAdditionalWorks', CollectionType::class, [
        'data'          => $quoteItem->getQuoteItemAdditionalWorks(),
        'label'         => false,
        'mapped'        => false,
        'entry_type'    => QuoteItemAdditionalWorkType::class,
        'entry_options' => ['label' => false],
        'by_reference'  => false,
        'allow_add'     => true,
        'allow_delete'  => true,
        'prototype'     => true,
    ]);
}

表单集合在表单上工作正常,但在提交并尝试从控制器中的学说实体中删除集合项目时,这些项目并未删除。删除项目的控制器代码看起来像

$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
    $em = $this->getDoctrine()->getManager();

    $quoteItem->setDrawingNumber($form->get('drawingNumber')->getData());
    $quoteItem->setDrawingRevision($form->get('drawingRevision')->getData());

    $updatedAdditionalWorkItems = $form->get('quoteItemAdditionalWorks')->getData()->unwrap();
    foreach ($quoteItem->getQuoteItemAdditionalWorks() as $existingAdditionalWorkItem) {
        if (false === $updatedAdditionalWorkItems->contains($existingAdditionalWorkItem)) {
            $em->remove($existingAdditionalWorkItem);
        }
    }

    $em->persist($quoteItem);
    $em->persist($workOrder);

    $em->flush();
}

我不知道这是否是我在 symfony 或 Doctrine 中做错的事情。从未映射的表单集合字段中的集合中删除项目时,我做错了什么?

请试试这个

foreach ($quoteItem->getQuoteItemAdditionalWorks() as $existingAdditionalWorkItem) 
{
    if (false === $updatedAdditionalWorkItems->contains($existingAdditionalWorkItem))
        {
            $quoteItem->getQuoteItemAdditionalWorks()->removeElement($existingAdditionalWorkItem);
            $em->remove($existingAdditionalWorkItem);
        }
}