2013-01-21 32 views
0

插入項目有兩個表,gameown。在own的實體,我創建OneToMany關係:的Symfony2和原則 - 我如何從連接表

/** @ORM\ManyToOne(targetEntity="Game") */ 
private $game; 

而且在game實體領域id也映射:

* @ORM\OneToMany(targetEntity="Own", mappedBy="game") 

現在,我有我的數據庫中插入新的數據有問題。我試着堅持簡單對象:

$gameown = new Own(); 
$gameown -> setGame('3'); 
$gameown -> setUpdated(date("Y-m-d H:i:s")); 

$em = $this->getDoctrine()->getEntityManager(); 
$em->persist($gameown); 
$em->flush(); 

但它不工作。 Symfony的是說,它必須是一個Game實例,而不是一個字符串。如何解決這個問題?

當我試試這個:

$gameown -> setGame($game->getId('3')); 

它插入不錯,但......空值。

+1

你需要考慮的對象,而不是列ID的條款。 $ gameown-> setGame($比賽);其中$遊戲是一個實際的遊戲實體或部分參考。考慮通過原則2手動去。 – Cerad

回答

2

或者

你可以做這種方式以及

$gameObject = $em->getRepository('YourBundle:Game')->findOneBy(array('id' => 3));

然後你可以使用

$gameown->setGame($gameObject);

1

其實,你必須使用一個遊戲對象,和學說就做好了你。 與對象認爲,不表。

首先,你必須檢索您的對象(從數據庫爲例):

$em = $this->getDoctrine()->getEntityManager(); 
$game = $em->getRepository('AppMonBundle:Game')->find(3); 

然後,您可以設置的關係:

$gameown->setGame($game);