2011-12-15 87 views
0

我將要瘋狂保存controller action beetween兩個entitiesSymfony2:保存Onetoone關係=>錯誤SQLSTATE [23000]完整性約束衝突

我有2個實體:

第一個被擴展FOSUser

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

    /** 
    * @var Namespace\LoginBundle\Entity\T $t 
    * 
    * @ORM\OneToOne(targetEntity="Namespace\LoginBundle\Entity\T", cascade={"persist"}) 
    */ 
    private $t; 
} 

第二個是:

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

    /** 
    * @ORM\OneToOne(targetEntity="Namespace\LoginBundle\Entity\User", cascade={"persist"}) 
    */ 
    private $user; 
} 

,當我登錄到我的應用程序和User是仍然保存到我的數據庫我有一排T字段null

進入我的控制器我有這樣的方法:

public function createAction() 
    {  
     $entity = new T();   

     // user 
     $user = $this->get('security.context')->getToken()->getUser(); 
     $entity->setUser($user); 
     $user->setT($entity); 

     $request = $this->getRequest(); 
     $form = $this->createForm(new TType(), $entity);   
     $form->bindRequest($request); 

     if ($form->isValid()) { 
      $em = $this->getDoctrine()->getEntityManager(); 

      $em->persist($entity);     
      $em->persist($entity->getUser()); 
      $em->persist($user->getT()); 

      $em->flush();        

      return $this->redirect($this->generateUrl('t_show', array('id' => $entity->getId()))); 
     } 

     return $this->render('NamespaceXXXXBundle:T:new.html.twig', array(
      'entity' => $entity, 
      'form' => $form->createView()     
     )); 
    } 

我不明白爲什麼,我有這樣的錯誤。

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`namespace`.`t`, CONSTRAINT `FK_58C6694C54EE02A4` FOREIGN KEY (`user_id`) REFERENCES `User` (`id`)) 

請幫我

山姆

回答

0

我也有問題,與此異常

request.CRITICAL: PDOException: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`mybundle`.`File`, CONSTRAINT `FK_70684D4DA76ED395` FOREIGN KEY (`user_id`) REFERENCES `JEP_File` (`id`)) (uncaught exception) 

的問題是在映射定義。我在File實體中使用了錯誤的映射。在我的情況下,目標實體對自己是mappihg - File。這就是爲什麼外鍵不匹配反轉表。

//... 
class File{ 

    @ORM\ManyToOne(targetEntity="File",inversedBy="files") 
//... 

//... 
class File{ 
/** 
* @ORM\ManyToOne(targetEntity="User",inversedBy="files") 
* @ORM\JoinColumn(name="owner_id",referencedColumnName="id") 
*/ 
protected $owner; 
//... 

希望,這會有所幫助。 嘗試查看dbs架構,不要忘記更新它

相關問題