我有两个Doctrine2实体:
class Product {
/**
* @ORM'OneToMany(targetEntity="ProductVendor", mappedBy="product")
*/
protected $productVendors;
//....
}
class ProductVendor {
/**
* @ORM'ManyToOne(targetEntity="Product", inversedBy="productVendors")
*/
protected $product;
//....
}
这些实体中的每一个都有标准的getter和setter,为了简洁起见,我省略了它们。我正在向产品供应商添加一个新产品,如下所示:
$myProductVendor->setProduct($myProduct);
当我循环浏览$myProduct的ProductVendor时,新的ProductVendors不在那里。它只包含该产品的现有ProductVendor。我的理解是,条令关系将负责将相关实体添加到关系的双方。我错过了什么?
由于它是双向的,您需要更新双方的关联。
例如
$myProductVendor->setProduct($myProduct);
$product->addProductVendor($myProductVendor);
为了获得更好的行为,请将其添加到级联的持久字段中:
public function addProductVendor('Project'YourBundle'Entity'ProductVendor $productVendor)
{
$productVendor->setProduct($this);
$this->productVendors[] = $productVendor;
return $this;
}