Doctrine 2: Saving Entity in Complex Relationship

て烟熏妆下的殇ゞ 提交于 2019-12-19 01:37:23

问题


I have the following relationships within my doctrine entities:

FavoriteRecipe

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

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

Recipe

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

User

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

In one of my controllers I have the following code:

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

But this throws an exception with the following message:

A new entity was found through a relationship that was not configured to cascade persist operations: Entities\User@00000000408bd010000000007cb1380e. Explicitly persist the new entity or configure cascading persist operations on the relationship.

How can I correctly create and save a FavoriteRecipe entity?


回答1:


Did you set the cascade option for all your relational entities? This is done by setting the cascade property for excample: cascade={"persist", "remove"}

Maybe this page:http://www.doctrine-project.org/docs/orm/2.0/en/reference/working-with-associations.html

Or these videos: http://www.zendcasts.com/many-to-many-with-doctrine-2/2011/03/ http://www.zendcasts.com/one-to-many-with-doctrine-2/2011/03/



来源:https://stackoverflow.com/questions/7319370/doctrine-2-saving-entity-in-complex-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!