从oneToMany关系中删除项目

时间:2013-04-24 16:35:41

标签: symfony doctrine-orm

我有以下图库实体

class Gallery
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var ArrayCollection
     * @ORM\OneToMany(targetEntity="Tessa\GalleryBundle\Entity\Photo", mappedBy="gallery", cascade={"persist", "remove"})
     */
    private $photos;

    /* ... */
}

gallerymanyToOne实体的PointOfInterest关系相关联。这是宣言

class PointOfInterest
{
 /* ... */
 /**
 * @ORM\ManyToOne(targetEntity="Tessa\GalleryBundle\Entity\Gallery", cascade={"persist", "remove"})
 * @ORM\JoinColumn(nullable=false)
 */
private $gallery;
 /* ... */

我还使用表单来更新PointOfInterest实体。这是表单声明

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
            ->add('name',           'text')
            ->add('gallery',        new GalleryType())
       ;
}

GalleryType声明。

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('photos', 'collection', array('type'          => new PhotoType(),
                                            'required'      => false,
                                            'allow_add'     => true,
                                            'allow_delete'  => true,
                                            'by_reference'  => false
                                            ))
    ;
}

当我编辑PoI时,我可以毫无问题地将照片添加到图库中,但我无法删除任何内容。

我试图挂钩图库PreUpdate,但它从未被调用过。我在removePhotos实体的Gallery方法中打印输出,照片将从图库中删除。然后我怀疑画廊永远不会坚持下去。

以下是我在编辑后保留PoI的代码。

private function handleForm($elem, $is_new)
{
    $form = $this->createForm(new CircuitType, $elem);

    $request = $this->get('request');
    if ($request->getMethod() == 'POST') {
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($elem);
            $em->flush();

            return $this->redirect($this->generateUrl('tessa_circuit_index'));
        }
    }

    return $this->render('TessaUserBundle:Circuits:add.'.'html'.'.twig',
        array(
            'form' => $form->createView(),
            'is_new' => $is_new,
        ));
}

1 个答案:

答案 0 :(得分:71)

关于处理此类情况有article in Symfony2 cookbook。由于您具有OneToMany关系,因此必须在控制器中手动删除相关对象。

修改: 或者您可以使用Doctrine's orphan removal功能。

class Gallery
{
    //...    

    /**
     * @ORM\OneToMany(targetEntity="Photo", mappedBy="gallery", cascade={"persist", "remove"}, orphanRemoval=true)
     */
    private $photos;

    //...

    public function removePhotos($photo)
    {
        $this->photos->remove($photo);
        $photo->setGallery(null);
    }
}