Symfony:OneToMany双向关系

时间:2016-03-07 13:51:34

标签: symfony one-to-many

这是我的实体"产品" :

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;
    }
}

而且,这是我的实体"提供" :

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,但在数据库中没有空。

帮助我...请...

1 个答案:

答案 0 :(得分:0)

Product实体中,您缺少引入包含*映射信息的docblock的第二个$offers字符:

/*
 * @ORM\OneToMany(targetEntity="ShopBundle\Entity\Offer", mappedBy="product", cascade={"persist", "remove", "merge"}, orphanRemoval=true)
 */
private $offers;

因此,PHP将这些行视为普通注释,而不是docblocks,这意味着Doctrine对它们一无所知。

只需将其更改为:

class Product
{
    // ...

    /**
     * @ORM\OneToMany(targetEntity="ShopBundle\Entity\Offer", mappedBy="product", cascade={"persist", "remove", "merge"}, orphanRemoval=true)
     */
    private $offers;

    // ...
}