原则 2:拯救复杂关系中的实体

发布于 2024-12-03 04:32:51 字数 1049 浏览 0 评论 0原文

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

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;

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

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

但这会引发异常并显示以下消息:

通过未配置的关系找到了新实体 级联持久化操作: 实体\用户@00000000408bd010000000007cb1380e。明确坚持 新实体或配置级联持久化操作 关系。

如何正确创建并保存 FavouriteRecipe 实体?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

靖瑶 2024-12-10 04:32:51

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

也许这个页面:https://www.doctrine-project.org/projects/doctrine-orm/en/2.9/reference/working-with-associations.html

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文