2011-09-06 44 views
8

我有我的原則實體內的下列關係:原則2:保存實體的複雜關係

FavoriteRecipe

/** 
* @ManyToOne(targetEntity="User", inversedBy="favoriteRecipes") 
*/ 
private $user; 

/** 
* @ManyToOne(targetEntity="Recipe", inversedBy="favoriteRecipes") 
*/ 
private $recipe; 

配方

/** 
* @OneToMany(targetEntity="FavoriteRecipe", mappedBy="user") 
*/ 
private $favoriteRecipes; 

用戶

/** 
* @OneToMany(targetEntity="FavoriteRecipe", mappedBy="user") 
*/ 
private $favoriteRecipes; 

在我的控制器之一,我有以下代碼:

$favoriteRecipe = new \Entities\FavoriteRecipe(); 
$favoriteRecipe->setRecipe($recipe); 
$favoriteRecipe->setUser($user); 
$this->_em->persist($favoriteRecipe); 
$this->_em->flush(); 

但是,這將引發具有以下消息的異常:

一個新的實體通過,這是一個關係找到未配置 以級聯持久操作: 實體\用戶@ 00000000408bd010000000007cb1380e。明確堅持 新實體或配置級聯堅持操作的關係 關係。

如何正確創建並保存FavoriteRecipe實體?

回答

7

您是否爲所有關係實體設置了級聯選項?這是通過設置excample級聯屬性來完成:級聯= { 「堅持」, 「刪除」}

也許這頁:http://www.doctrine-project.org/docs/orm/2.0/en/reference/working-with-associations.html

或者這些視頻: http://www.zendcasts.com/many-to-many-with-doctrine-2/2011/03/ http://www.zendcasts.com/one-to-many-with-doctrine-2/2011/03/

+1

要哪一方該關聯是否添加級聯選項?擁有方還是反方? – moteutsch

+0

這取決於你想要的行爲,但在你的情況下,我認爲反面。我會說試試看,看看數據庫中發生了什麼。 –

+2

我會添加「並回到這裏分享你的發現」。人們幫助你,別忘了幫助別人:) – Ninj

相關問題