多媒体,图库和GalleryMultimedia。
Multimedia和Gallery与GalleryMultimedia有一对多的关系,它拥有multimedia_id,gallery_id和position。
在我的MultimediaAdmin中,我添加了Galleries列表,如下所示:
->with('Thematic Galleries')
->add('gallery', 'entity', array(
'class' => 'ACME\MyBundle\Entity\Gallery',
'property' => 'name',
'multiple' => true,
'expanded' => true,
'mapped' => false,))
->end()
现在我坚持将选定的Gallery作为GalleryMultimedia对象进行持久化。在我的多媒体模型中,我有下面的函数,我很乐意通过GalleryMultimedia对象进行持久化但是无法弄清楚如何。
public function setGalleries($galleries)
{
if (count($galleries) > 0) {
foreach ($galleries as $gallery)
{
$this->addGallery($gallery);
}
}
return $this;
}
出于解压,我在MultimediaAdmin.php中添加了以下代码
public function prePersist($multimedia)
{
$this->preUpdate($multimedia);
}
public function preUpdate($multimedia)
{
$multimedia->setFiles($multimedia->getFiles());
$this->saveGalleries($multimedia);
}
public function saveGalleries($multimedia)
{
$galleryies = $this->getForm()->get('gallery')->getData();
$container = $this->getConfigurationPool()->getContainer();
$em = $container->get('doctrine')->getManager();
$existing_arr = array();
$existing = $em->getRepository('ACMEMyBundle:GalleryMultimedia')->findBy(array('multimedia' => $multimedia));
$gals = array();
foreach($existing as $exist)
{
$existing_arr[] = $exist->getGallery()->getId();
}
foreach($galleryies as $gallery)
{
if(in_array($gallery->getId(),$existing_arr))
{
continue;
}
else
{
$gm = new \ACME\MyBundle\Entity\GalleryMultimedia();
$gm->setGallery($gallery);
$gals[] = $gm;
$multimedia->setGalleries($gals);
}
}
}
有人可以帮助我可怜的灵魂吗?
答案 0 :(得分:1)
我通过像这样坚持postPersist来解决这个问题
public function postPersist($multimedia)
{
$this->postUpdate($multimedia);
}
public function postUpdate($multimedia)
{
$this->saveGalleries($multimedia);
}
希望这会帮助那些人
答案 1 :(得分:0)
我用对象做的方式:
public function preUpdate($object)
{
$this->updateCountries($object);
}
public function updateCountries(\AppBundle\Entity\Product $object){
$container = $this->getConfigurationPool()->getContainer();
$em = $container->get('doctrine')->getManager();
$form_countries = $this->getForm()->get('Country')->getData();
//form_countries is a Doctrine\Common\Collections\ArrayCollection
$object_countries = $object->getCountries();
//object_countries is a collection of \AppBundle\Entity\CountryProduct
$list = array();
foreach($object_countries as $country){
if(!$form_countries->contains($country->getCountry())){
//remove objects not in the form
$em->remove($country);
} else {
//save the others to not re add them
$list[] = $country->getCountry();
}
}
foreach($form_countries as $country){
if(!in_array($country, $list)){
//add everyone in the form but not in the list
$countryProduct = new \AppBundle\Entity\CountryProduct();
$countryProduct->setProduct($object);
$countryProduct->setCountry($country);
$countryProduct->setValuation(1);
$em->persist($countryProduct);
}
}
$em->flush();
}