Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine 2: Saving Entity in Complex Relationship

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?

like image 655
moteutsch Avatar asked Sep 06 '11 11:09

moteutsch


1 Answers

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

Maybe this page:https://www.doctrine-project.org/projects/doctrine-orm/en/2.9/reference/working-with-associations.html

like image 97
Kees Schepers Avatar answered Nov 18 '22 13:11

Kees Schepers