2011-02-05 96 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

回答