我有一個多對多關係的問題。我調試了我的表單,我發現所選對象實際上是在表單驗證之後在實體對象中,但它永遠不會保存到數據庫中,所以必須存在與我的映射代碼有關的問題,但是我從工作中複製粘貼一個剛剛取代的領域和路徑...symfony2將數據添加到對象,但從不堅持DB(原則ORM多對多)
這裏的公司對象的相關代碼
/**
* @ORM\ManyToMany(targetEntity="BizTV\ContentManagementBundle\Entity\Template", inversedBy="companies")
* @ORM\JoinTable(name="templatePermissions")
*/
private $templatePermissions;
/**
* Add templatePermissions
*
* @param BizTV\ContentManagementBundle\Entity\Template $templatePermissions
*/
public function addTemplate(\BizTV\ContentManagementBundle\Entity\Template $templatePermissions)
{
$this->templatePermissions[] = $templatePermissions;
}
和模板對象
/**
* @ORM\ManyToMany(targetEntity="BizTV\BackendBundle\Entity\company", mappedBy="templatePermissions")
*/
private $companies;
/**
* Add companies
*
* @param BizTV\BackendBundle\Entity\company $companies
*/
public function addCompany(\BizTV\BackendBundle\Entity\company $companies)
{
$this->companies[] = $companies;
}
/**
* Get companies
*
* @return Doctrine\Common\Collections\Collection
*/
public function getCompanies()
{
return $this->companies;
}
代碼更新(和創造是相似的,並具有同樣的問題)只是一個標準...
public function updateAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository('BizTVContentManagementBundle:Template')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Template entity.');
}
$editForm = $this->createForm(new TemplateType(), $entity);
$deleteForm = $this->createDeleteForm($id);
$request = $this->getRequest();
$editForm->bindRequest($request);
if ($editForm->isValid()) {
//DEBUG
// foreach($entity->getCompanies() as $c) {
// echo $c->getCompanyName();
// }
// die;
$em->persist($entity);
$em->flush();
$this->getRequest()->getSession()->setFlash('success', 'Template '.$entity->getId().' har uppdaterats.');
return $this->redirect($this->generateUrl('listTemplates'));
}
這裏是我的形式,就像我說的,它完美的把東西進入我的對象(模板實體),但它並不會持久化到數據庫...
$builder
->add('companies', 'entity', array(
'label' => 'Företag som har tillgång till mallen',
'multiple' => true, // Multiple selection allowed
'expanded' => true, // Render as checkboxes
'property' => 'company_name',
'class' => 'BizTV\BackendBundle\Entity\company',
))
;
上午什麼我錯過了?
怎麼樣讀一點這個:http://docs.doctrine-project.org/en/2.0.x/reference/association-mapping.html? – shadyyx
將做到這一點... –