【问题标题】:Doctrine2.3 and OneToOne cascade persist doesn't seem to workDoctrine2.3 和 OneToOne 级联持续似乎不起作用
【发布时间】:2013-08-09 09:42:39
【问题描述】:

我有两个要单向映射 OneToOne 的实体(User 和 UserPreferences)。

代码如下所示:

/**
 * @ORM\Table("users")
 * @ORM\Entity
 */
class User
{
    /**
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     */
    protected $id;

    ...

    /**
     * @ORM\Column(name="user_preferences_id", type="integer")
     * @ORM\OneToOne
     * (
     *      targetEntity="UserPreferences",
     *      cascade={"persist"}
     * )
     */
    protected $userPreferences;

    public function __construct() {
        $this->userPreferences = new UserPreferences();
    }
}


/**
 * @ORM\Table("user_preferences")
 * @ORM\Entity
 */
class UserPreferences extends UserPreferencesEntity
{
    /**
     * @ORM\Id
     * @ORM\Column(name="user_id", type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    ...
}

现在当一个新用户被创建时,userPreferences 被一个新的 UserPreferences 对象初始化。当试图坚持user 时,Doctrine 抛出一个异常,声称

A new entity was found through the relationship '...\Entity\User#userPreferences' that was not configured to cascade persist operations for entity: ...\Entity\UserPreferences@000000003ae25e5700000000a6eaafc9. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist this association in the mapping for example @ManyToOne(..,cascade={"persist"}).

但是我还应该做什么呢? User#userPreferences 配置为级联持久化,但事实并非如此。我这里有什么问题吗?

【问题讨论】:

  • 没有那个注解属性你试过了吗?
  • 没有哪个注解属性?

标签: php mysql orm doctrine-orm


【解决方案1】:

好的,找到了解决方案:

/**
 * User
 *
 * @ORM\Table("users")
 * @ORM\Entity
 */
class User extends UserEntity
{
    ...

    /**
     * @ORM\OneToOne
     * (
     *      targetEntity="UserPreferences",
     *      cascade={"persist", "remove"},
     *      inversedBy="user"
     * )
     */
    protected $userPreferences;
}

/**
 * @ORM\Table("user_preferences")
 * @ORM\Entity
 */
class UserPreferences extends UserPreferencesEntity
{
    /**
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue
     */
    protected $id;

    /**
     * @var int
     *
     * @ORM\OneToOne(targetEntity="User", mappedBy="id", cascade={"persist", "remove"})
     */
    protected $user;

    ...
}

首先,我必须指定 mappedBy 和 inversedBy(我之前已经尝试过,但方向错误 - mappedBy 在拥有方,inversedBy 在反面)。另外我认为反面不需要单独的 id,我也尝试使用拥有方的 id (User#id) 作为主键。

【讨论】:

  • targetEntity的id
【解决方案2】:

Bug 与

 * @ORM\Column(name="user_preferences_id", type="integer")

您的代码应包含

 * @ORM\JoinColumn(name="user_preferences_id", referencedColumnName="id")

而不是这个。

【讨论】:

  • 而不是什么
  • @Daniel 请更正您的答案,而不是评论更正。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-25
  • 2021-01-31
  • 1970-01-01
  • 1970-01-01
  • 2012-03-21
相关资源
最近更新 更多