学说关联 坚持时的完整性约束


Doctrine associations Integrity Constraint when persisting

我有许多@ManyToMany关联映射可以正常工作,但是当尝试保留具有双向@OneToOne@ManyToOne关联的实体时,Doctrine 会抛出以下错误:

Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'uid' cannot be null'
实体

/实体库.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;
}

实体/用户.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;
}

实体/利益.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 作为主键,因为正在持久化的数据集来自所有用户都有唯一uid的 API。 我不确定为什么我看到'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错误。 但是,如果我删除关联,实体将正确保留并更新数据库。

我错过了什么吗?

根据您的实体类,兴趣是关系的拥有方。当您尝试保留 Interest 对象时,它也需要 User 对象保留。这可能是因为您没有为感兴趣的用户映射允许 null。

为了使持久发生,请将 User 对象附加到 Interest 对象或允许该映射为 null(不建议这样做)。