2011-02-05 29 views
2

我完全不熟悉Doctrine 2(也適用於ORM),並且在更新集合時遇到問題。我覺得這是一個典型的noob問題。修改Doctrine集合不會影響數據庫表

我需要客戶和主機。每臺主機都分配給一些客戶,每個客戶可以擁有多臺主機。我(簡體)班如下:

/** 
* @Entity @Table(name="Customers") 
*/ 
class Customer 
{ 
    /** @Id @Column(type="integer") @GeneratedValue */ 
    private $id; 

    /** @OneToMany(targetEntity="Host", mappedBy="cust_id") */ 
    private $hosts = null; 

    public function __construct() 
    { 
     $this->hosts = new ArrayCollection(); 
    } 

    public function addHost($host) 
    { 
     $this->hosts[] = $host; 
    } 

    // plus getters/setters... 
} 

/** 
* @Entity @Table(name="Hosts") 
*/ 
class Host 
{ 
    /** @Id @Column(type="integer") @GeneratedValue */ 
    private $id; 

    /** @ManyToOne(targetEntity="Customer", inversedBy="hosts") */ 
    private $cust_id; 

    // plus getters/setters... 
} 

我的數據庫(SQLite的)表如下:

客戶:ID,...

主持人:ID,cust_id_id,...

我可以創建新的客戶和主機用下面的代碼:

$customer = new Customer(); 
$em->persist($customer); 
$em->flush(); 

但是,當我嘗試添加一些主機給客戶,使用以下代碼:

$customer = ... // obtain a customer object - that works. 
$host = ... // obtain a host object - that works. 
$customer->addHost($host); 
$em->persist($customer); 
$em->flush(); 

沒有任何反應。我的意思是我看到我的數據庫沒有變化(受影響的主機的cust_id_id仍然是空的)。我想爲某個使用者添加一個新主機,並在主機表中正確設置cust_id_id列。

我在做什麼錯?


更新:

我想,一對多的關係必須要反的一面,因爲它聲明爲擁有方造成了我的教訓抱怨未知的選項「inversedBy」。所以,我決定離開客戶爲反方,並且主機作爲擁有方,並修改客戶 - > addHost方法如下:

public function addHost($host) 
{ 
    $host->setCustomerId($this->id); 
    $this->hosts[] = $host; 
} 

現在,調用$ EM->的flush()後,我得到以下錯誤:

Uncaught exception 'InvalidArgumentException' with message 'A new entity was found through a relationship that was not configured to cascade persist operations: @. Explicitly persist the new entity or configure cascading persist operations on the relationship.'

+0

IMO,您應該將`Host :: $ cust_id`重命名爲`Host :: $ customer`。 – Cobby 2011-02-06 23:45:07

+0

這與[此問題]非常相似(http://stackoverflow.com/questions/4928170/getting-associated-entries-in-doctrine-2) – xzyfer 2011-02-08 09:52:04

回答