Doctrine2.3和OneToOne级联持续存在似乎不起作用

dwa*_*orf 5 php mysql orm doctrine-orm

我有两个entite(User和UserPreferences),我想要单向映射OneToOne.

代码看起来像这样:

/**
 * @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;

    ...
}
Run Code Online (Sandbox Code Playgroud)

现在,当创建新用户时,将使用新的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"}).

但我还应该做些什么呢?用户#userPreferences配置为级联持久但不支持.我在这里弄错了吗?

dwa*_*orf 6

好的找到了解决方案:

/**
 * 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;

    ...
}
Run Code Online (Sandbox Code Playgroud)

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