2013-10-18 54 views
0

當完整性約束我有一些@ManyToMany關聯映射,試圖堅持的實體或者是雙向@OneToOne@ManyToOne協會然而當工作,因爲他們應該,學說引發以下錯誤:主義協會堅持

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(); 

當我運行這個與用戶與利益之間的@OneToOne關聯,我堅持時,你得到Integrity Constraint violation錯誤。但是,如果我刪除關聯,實體將正確保持並更新數據庫。

我錯過了什麼嗎?

+0

該原則引用映射可以設置僅引用標識符字段。在您的示例字段「uid」中 - 不是標識符字段。爲什麼你的創建索引@Table(name =「interest」,indexes = {@ Index(name =「id」,columns = {「id」})})。這個索引將會自動創建爲doctrine。爲了更好的解決方案:爲控件創建和更新的字段創建一個自定義特徵,並在每個實體中使用它自己。 – ZhukV

+0

@ZhuKV - 感謝您看一下,有沒有一種使用自定義字符串作爲標識符字段的方法? – dcd0181

回答

0

根據您的實體類,興趣是關係的擁有方。當你試圖持久興趣對象時,它也期望一個用戶對象持久。這可能是因爲您沒有允許興趣用戶映射爲空。

爲了堅持發生,請將User對象附加到Interest對象或允許該映射爲null(不建議這樣做)。