简体   繁体   中英

How to remove galleryhasmedia from gallery sonatamediabundle

I am trying to remove galleryhasmedia from gallery.

However gallery entity doesn't have removegalleryhasmedia or something.

so I did a clumsy way, but it doesnt work.

$em = $this->getDoctrine()->getManager();

$firstGhmArray = $gallery->getGalleryHasMedias();
echo count($gallery->getGalleryHasMedias()) // before count
$afterGhmArray = array();
foreach ($firstGhmArray as $ghm){

        if ($ghm->getId() == $id){ // id is the target id to delete
                //delete    
        }
        else {
            array_push($afterGhmArray , $ghm);
        }
        $gallery->setGalleryHasMedias($afterGhmArray);
    }
echo count($gallery->getGalleryHasMedias()) // after count
$em->persist($gallery);
$em->flush();

I think if galleryHasMedias are normal array collection.

I can delete the element with this procedure.

I need to do something more for galleryhasmedia??

You can override the Gallery entity and add this function to it :

    public function clearGalleryHasMedias()
    {
        $this->galleryHasMedias->clear();
    }

galleryHasMedias field is an ArrayCollection which can be cleared using the clear method. Its weird tho that setting an empty array doesn't clear work but i guess my solution is worth the shot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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