教义协会在坚持时的诚信约束

时间:2013-10-18 19:40:05

标签: php doctrine-orm doctrine associations entity

我有许多@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;
}

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

实体/ 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();

当我使用User和Interest之间的@OneToOne关联运行时,我会在持久时收到Integrity Constraint violation错误。但是,如果删除关联,则实体会正确保留并更新数据库。

我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

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

为了使持久化发生,要么将User对象附加到Interest对象,要么允许该映射为null(不推荐)。

相关问题