[英]Persisting entity with Doctrine association
I'm having trouble trying to persist an entity with an association using Doctrine. 我在尝试使用Doctrine保留与关联的实体时遇到麻烦。
Here's the mapping on my owning side: (User.php) 这是我自己的映射:(User.php)
/** @Role_id @Column(type="integer") nullable=false */
private $role_id;
/**
* @ManyToOne(targetEntity="Roles\Entities\Role")
* @JoinColumn(name="role_id", referencedColumnName="id")
*/
private $role;
There's no mapping on the inverse side, I tried with (OneToMany)
and it didn't seem to make a difference. 在反面没有映射,我尝试了
(OneToMany)
,但似乎没有什么不同。
Basically, I'm passing a default value of 2 (integer)
to a method setRole_id
but it shows up as blank when I actually go to persist the entity which causes a MySQL error as that column doesn't allow nulls
. 基本上,我将默认值2
(integer)
传递给方法setRole_id
但是当我实际去保留会导致MySQL错误的实体时,它显示为空白,因为该列不允许nulls
。
Edit 1: 编辑1:
Literally just persisting this for role_id 从字面上看只是坚持为role_id
$this->user->setRole_id( 2 ); $ this-> user-> setRole_id(2);
Cheers, 干杯,
Ewan 伊万
Your mapping seems incorrect. 您的映射似乎不正确。 Try to rewrite it as follows:
尝试如下重写:
/**
* @ManyToOne(targetEntity="Roles\Entities\Role")
* @JoinColumn(name="role_id", referencedColumnName="id", nullable=false)
*/
private $role;
In other words, you only need to describe the role_id
as the join column of your relationship. 换句话说,您只需要将
role_id
描述为关系的连接列。 You don't need to map it as a "normal" column. 您无需将其映射为“常规”列。 Then just write and use a regular setter declared like the one below:
然后,只需编写并使用如下所示的常规setter:
public function setRole(Roles\Entities\Role $role) {
$this->role = $role;
}
Use the above instead of $this->user->setRole_id(2)
and persist your user entity. 使用上面的内容代替
$this->user->setRole_id(2)
并保留您的用户实体。 Doctrine should automatically take care of storing the correct entity ID in the foreign key field for you. 教义应自动为您在外键字段中存储正确的实体ID。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.