我有两个实体(用户和用户首选项),我想单向映射一对一。
代码看起来像这样:
/**
* @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 配置为级联持久化,但事实并非如此。我这里有什么问题吗?
好的找到了解决方案:
/**
* 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) 作为主键。
- http://docs.doctrine-project.org/en/latest/reference/unitofwork-associations.html
- http://docs.doctrine-project.org/en/latest/reference/association-mapping.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)