将实体添加到双向DoctrineCollection中

I have 2 Doctrine2 entities:

class Product {
   /**
   * @ORM\OneToMany(targetEntity="ProductVendor", mappedBy="product")
   */
   protected $productVendors;

   //....
}

class ProductVendor {
   /**
   * @ORM\ManyToOne(targetEntity="Product", inversedBy="productVendors")
   */
   protected $product;

   //....
}

Each of these entities has standard getters and setters which I left out for brevity. I am adding a new Product to a ProductVendor like this:

$myProductVendor->setProduct($myProduct);

When I then loop through the ProductVendors for $myProduct, the new ProductVendor is not there. It only contains the existing ProductVendors for that product. It was my understanding that the Doctrine relationship would take care of adding the related entities to both sides of the relationship. What am I missing?

For a better behaviour add this on your cascaded persist fields :

public function addProductVendor(\Project\YourBundle\Entity\ProductVendor $productVendor)
{
    $productVendor->setProduct($this);
    $this->productVendors[] = $productVendor;

    return $this;
}

As it's bi-directional you need to update the association on both sides.

e.g.

$myProductVendor->setProduct($myProduct);
$product->addProductVendor($myProductVendor);