学说2:在复杂关系中拯救实体

mot*_*sch 8 php one-to-many doctrine-orm

我的学说实体内有以下关系:

FavoriteRecipe

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

/**
 * @ManyToOne(targetEntity="Recipe", inversedBy="favoriteRecipes")
 */
private $recipe;
Run Code Online (Sandbox Code Playgroud)

食谱

/**
 * @OneToMany(targetEntity="FavoriteRecipe", mappedBy="user")
 */
private $favoriteRecipes;
Run Code Online (Sandbox Code Playgroud)

用户

/**
 * @OneToMany(targetEntity="FavoriteRecipe", mappedBy="user")
 */
private $favoriteRecipes;
Run Code Online (Sandbox Code Playgroud)

在我的一个控制器中,我有以下代码:

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

但是这会抛出以下消息的异常:

通过未配置为级联持久操作的关系找到新实体:Entities\User @ 00000000408bd010000000007cb1380e.明确保留新实体或在关系上配置级联持久操作.

如何正确创建和保存FavoriteRecipe实体?

Kee*_*ers 7

您是否为所有关系实体设置了级联选项?这是通过为excample设置cascade属性来完成的:cascade = {"persist","remove"}

也许这个页面: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-二千〇一十一分之二/ 03 /

  • 我会添加"并回到这里分享你的发现".人们帮助了你,别忘了帮助别人:) (3认同)