开发者

Modifying Doctrine collections doesn't affect database tables

I'm completely new to Doctrine 2 (and to ORM too), and I have a problem with updating collections. I feel it's a typical noob question.

I need customers and hosts. Each host is assigned to some customer, and each customer can have many hosts. My (simplified) classes are as follows:

/**
 * @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...
}

My database (SQLite) tables are as follows:

Customers: id, ...

Hosts: id, cust_id_id, ...

I can create new customers and hosts with the following code:

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

But when I try to add some host to a customer, with this code:

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

nothing happens. I mean I see no changes in my database (cust_id_id for the affected host is still empty). I'd like to add a new host to some consumer, and have the cust_id_id column properly set in the Hosts table.

What am I doing wrong?


Update:

I suppose that OneToMany relation have to be the inverse side, since declaring it as the owning side causes my doctrine to complain about unknown option "inversedBy". So I decided to leave the Customer as the inverse side, and the Host as the owning side, and modify the Customer->addHost method as follows:

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

Now, after calling $em->flu开发者_如何学JAVAsh() I get the following error:

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.'


You defined Customer#hosts as the inverse side. Only the owning side is considered when saving data to the database. See the manual chapter on this issue.

http://www.doctrine-project.org/docs/orm/2.0/en/reference/association-mapping.html#owning-side-and-inverse-side

In your case if you want to have Customer#addHosts rather than Host#addCustomer you have to switch the "mappedBy" and "inversedBy" keywords on the two entities.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜