[英]Symfony: OneToMany Bidirectionnal Relation
这是我的实体“产品”:
class Product
{
/**
* @var int
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/*
* @ORM\OneToMany(targetEntity="ShopBundle\Entity\Offer", mappedBy="product", cascade={"persist", "remove", "merge"}, orphanRemoval=true)
*/
private $offers;
/*
* Constructeur
*/
public function __construct()
{
$this->offers = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add offer
* @param \ShopBundle\Entity\Offer $offer
* @return Product
*/
public function addOffer(\ShopBundle\Entity\Offer $offer)
{
$this->offers[] = $offer;
return $this;
}
/**
* Remove offer
* @param \ShopBundle\Entity\Offer $offer
*/
public function removeOffer(\ShopBundle\Entity\Offer $offer)
{
$this->offers->removeElement($offer);
}
/**
* Get parameters
* @return \Doctrine\Common\Collections\Collection
*/
public function getOffers()
{
return $this->offers;
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
}
而且,这是我的实体“ Offer”:
class Offer
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity="ShopBundle\Entity\Product", inversedBy="offers", cascade={"persist", "merge"})
* @ORM\JoinColumn(name="product_id", referencedColumnName="id", nullable=false)
*/
private $product;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set product
*
* @param \ShopBundle\Entity\Product $product
*
* @return Offer
*/
public function setProduct(\ShopBundle\Entity\Product $product)
{
$this->product = $product;
return $this;
}
/**
* Get product
*
* @return \ShopBundle\Entity\Product
*/
public function getProduct()
{
return $this->product;
}
}
何时,我在控制器中使用$ product = $ em-> getRepository('ShopBundle:Product')-> find($ id);获得对象。
然后,$ product-> getOffers()返回null,但在数据库中不存在null。
请帮帮我 ...
在您的Product
实体中,您缺少第二个*
字符,该字符引入了包含$offers
映射信息的docblock:
/*
* @ORM\OneToMany(targetEntity="ShopBundle\Entity\Offer", mappedBy="product", cascade={"persist", "remove", "merge"}, orphanRemoval=true)
*/
private $offers;
因此,PHP将这些行视为普通注释,而不是docblock,这意味着Doctrine对它们一无所知。
只需将其更改为如下所示:
class Product
{
// ...
/**
* @ORM\OneToMany(targetEntity="ShopBundle\Entity\Offer", mappedBy="product", cascade={"persist", "remove", "merge"}, orphanRemoval=true)
*/
private $offers;
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.