我有一个 M2M 关系,但是当我创建一个项目时,关系没有保存,我找不到问题出在哪里。该模型:
class Serie
{
/**
* @ORM\ManyToMany(targetEntity="Magazine", mappedBy="series")
* */
protected $magazines;
/**
* Constructor
*/
public function __construct()
{
$this->magazines = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add magazines
*
* @param MyList\DBBundle\Entity\Magazine $magazines
* @return Serie
*/
public function addMagazine(\MyList\DBBundle\Entity\Magazine $magazines)
{
$this->magazines[] = $magazines;
return $this;
}
/**
* Remove magazines
*
* @param MyList\DBBundle\Entity\Magazine $magazines
*/
public function removeMagazine(\MyList\DBBundle\Entity\Magazine $magazines)
{
$this->magazines->removeElement($magazines);
}
/**
* Get magazines
*
* @return Doctrine\Common\Collections\Collection
*/
public function getMagazines()
{
return $this->magazines;
}
}
杂志类:
class Magazine
{
/**
* @ORM\ManyToMany(targetEntity="Serie" , inversedBy="magazines")
* @ORM\JoinTable(name="magazines_series")
* */
protected $series;
public function __construct()
{
$this->series = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add series
*
* @param MyList\DBBundle\Entity\Serie $series
* @return Magazine
*/
public function addSerie(\MyList\DBBundle\Entity\Serie $serie)
{
$serie->addMagazine($this);
$this->series[] = $serie;
return $this;
}
/**
* Remove series
*
* @param MyList\DBBundle\Entity\Serie $series
*/
public function removeSerie(\MyList\DBBundle\Entity\Serie $series)
{
$this->series->removeElement($series);
}
/**
* Get series
*
* @return Doctrine\Common\Collections\Collection
*/
public function getSeries()
{
return $this->series;
}
}
控制器类 SerieController 扩展控制器 { public function newAction() { $entity = new Serie(); $form = $this->createForm(new SerieType(), $entity);
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Creates a new Serie entity.
*
* @Route("/create", name="serie_create")
* @Method("POST")
* @Template("DBBundle:Serie:new.html.twig")
*/
public function createAction(Request $request)
{
$entity = new Serie();
$form = $this->createForm(new SerieType(), $entity);
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('serie_show', array('id' => $entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
}
和表格:
class SerieType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title')
->add('start')
->add('end')
->add('type')
->add('status')
->add('magazines','entity',array(
'class' => 'DBBundle:Magazine',
'multiple' => true,
'property' => 'name'
))
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'MyList\DBBundle\Entity\Serie'
));
}
public function getName()
{
return 'mylist_dbbundle_serietype';
}
}
我知道对此有一些问题(即Symfony2-Doctrine: ManyToMany 关系未保存到数据库),但它们都没有解决我的问题。