【发布时间】:2013-10-18 19:40:04
【问题描述】:
我有许多 @ManyToMany 关联映射可以正常工作,但是当尝试使用双向 @OneToOne 或 @ManyToOne 关联来持久化实体时,Doctrine 会引发以下错误:
Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'uid' cannot be null'
实体/EntityBase.php
namespace Entities;
class EntityBase{
/** @Column(type="integer", columnDefinition="INT AUTO_INCREMENT NOT NULL") */
protected $id;
/** @Column(type="datetime") */
protected $created;
/** @Column(type="datetime") */
protected $updated;
}
Entities/User.php
namespace Entities;
/**
* @Entity(repositoryClass="Repositories\UserRepository")
* @Table(name="users", indexes={@Index(name="id", columns={"id"})})
*/
class User extends EntityBase{
/** @Id @Column(type="string") */
protected $uid;
/** @Column(type="string", nullable=true) */
protected $first_name;
/** @Column(type="string", nullable=true) */
protected $middle_name;
/** @Column(type="string", nullable=true) */
protected $last_name;
/** @OneToOne(targetEntity="Entities\Interest", mappedBy="user") **/
private $interest;
}
Entities/Interest.php
namespace Entities;
/**
* @Entity(repositoryClass="Repositories\InterestRepository")
* @Table(name="interests", indexes={@Index(name="id", columns={"id"})})
*/
class Interest extends EntityBase{
/** @Id @Column(type="string") */
protected $uid;
/** @Column(type="string", nullable=true) */
protected $interests;
/**
* @OneToOne(targetEntity="Entities\User", inversedBy="interest")
* @JoinColumn(name="uid", referencedColumnName="uid")
**/
private $user;
public function setUserId($uid){
$this->uid = $uid;
}
public function setInterests($interests){
$this->interests = $interests;
}
}
上面的关联应该表明一个用户可以有一个兴趣,一个兴趣属于一个用户。我使用uid 作为主键而不是id,因为持久化的数据集来自一个API,其中所有用户都有一个唯一的uid。我不确定为什么我得到'uid' cannot be null,因为我已经转储了数据集并且uid 肯定是作为字符串传递的。
这是我的交互代码:
//Example
$data = array('uid' => '10298564', 'interests' => 'Creative Art');
if(!$interest = $entityManager->getRepository('Entities\Interest')->findOneBy(array('uid' => $data['uid']))){
$interest = new Entities\Interest();
}
$interest->setUserId($data['uid']);
$interest->setInterest($user['interests']);
$entityManager->persist($interest);
$entityManager->flush();
当我使用用户和兴趣之间的@OneToOne 关联运行此程序时,我在坚持时收到Integrity Constraint violation 错误。但是,如果我删除关联,实体会正确保留并更新数据库。
我错过了什么吗?
【问题讨论】:
-
学说引用映射可以设置仅引用标识符字段。在您的示例字段“uid”中 - 不是标识符字段。以及为什么要创建索引@Table(name="interests", indices={@Index(name="id", columns={"id"})})。该索引将使用教义自动创建。为了更好的解决方案:为控件创建和更新字段创建一个自定义特征,并在每个实体中使用它自己。
-
@ZhuKV - 感谢您的浏览,有没有使用自定义字符串作为标识符字段的方法?
标签: php doctrine-orm doctrine associations entity