Symfony 教义2一元逆持续性

Symfony 教义2一元逆持续性,symfony,doctrine-orm,Symfony,Doctrine Orm,好的。。。问这个我觉得很愚蠢,但是 我有一个与以下实体的实体: 供应商: /** * @ORM\OneToMany(targetEntity="SRC\Bundle\MarketingBundle\Entity\Ad", mappedBy="vendor", cascade={"all"}) * * @var Collection|Ad[] */ protected $ads; /** * Returns all vendor ads. * * @return Collectio

好的。。。问这个我觉得很愚蠢,但是

我有一个与以下实体的实体:

供应商:

/**
 * @ORM\OneToMany(targetEntity="SRC\Bundle\MarketingBundle\Entity\Ad", mappedBy="vendor", cascade={"all"})
 *
 * @var Collection|Ad[]
 */
protected $ads;

/**
 * Returns all vendor ads.
 *
 * @return Collection|Ad[]
 */
public function getAds()
{
    return $this->ads;
}

/**
 * Sets all vendor ads.
 *
 * @param Collection $ads
 */
public function setAds(Collection $ads)
{
die("SET ADS. DIE! DIE!");
    $this->ads = $ads;

    return $this;
}

/**
 * Adds vendor ad.
 *
 * @param Ad $ad
 */
public function addAd(Ad $ad)
{
    if (!$this->hasAd($ad)) {
        $ad->setVendor($this);
        $this->ads->add($ad);
    }

    return $this;
}

/**
 * Removes vendor ad.
 *
 * @param Ad $ad
 */
public function removeAd(Ad $ad)
{
    if ($this->hasAd($ad)) {
        $this->ads->removeElement($ad);
        $ad->setVendor(null);
    }

    return $this;
}

/**
 * Checks whether vendor has given ad.
 *
 * @param Ad $ad
 *
 * @return Boolean
 */
public function hasAd(Ad $ad)
{
    return $this->ads->contains($ad);
}
广告:


问题存在于供应商CRUD中,当我更新ads时,setAds从未被调用,正如您可以看到的那样,那里的die从未被执行。我做错了什么?

更喜欢在集合中添加方法

public function addAd(\SRC\Bundle\MarketingBundle\Entity\Ad $ad)
{
    if(!$this->ads->contains($ad)) {
        $this->ads[] = $ad;
    }
    return $this;
}

public function removeAd(\SRC\Bundle\MarketingBundle\Entity\Ad $ad)
{
    $this->ads->removeElement($ad);
}

public function getAds()
{
    return $this->ads;
}
我假设您可能在Ad类中调用一个setVendor方法来执行关系,以同步双方,执行如下操作:

public function setVendor(Vendor $vendor){
    $this->vendor = $vendor;
    $vendor->addAd($this);
    return $this;
}
您还应该在供应商构造函数中初始化ArrayCollection:

public __construct()
{
    $this->ads = new \Doctrine\Common\Collections\ArrayCollection();
}

你什么时候打电话给setAds的?您使用哪种方法“更新广告”?$vendor->addAd$这可能有点太多逻辑,无法放入您的实体中。kriswallsmith建议在prePersist/preUpdate上设置一个事件侦听器,以将该逻辑与实际模型分开。听起来是个好主意,但对于一个简单的东西来说,这需要很多代码:它还允许您删除实体,并使用条令迁移重新创建它们,而不必担心丢失现有的自定义getter/setter。
public __construct()
{
    $this->ads = new \Doctrine\Common\Collections\ArrayCollection();
}