在我的模型中

Terrain.php

/**
* @ORM\Entity
* @ORM\HasLifecycleCallbacks()
*/
class Terrain
{

 /**
  * @var lots
  *
  * @ORM\OneToMany(targetEntity="Lot", mappedBy="terrain")
  */
  private $lotes;

  /**
   * @ORM\PreRemove
   */
  public function deleteAllLots()
  {
    $lots = $this->getLots();

    foreach ($lots as $lot) {
        $this->lots->removeElement($lot);
    }
  }

}

Lot.php
/**
* @ORM\Entity
* @ORM\HasLifecycleCallbacks()
*/
class Lot
{

 /**
  * @var Terrain
  *
  * @ORM\ManyToOne(targetEntity="Terrain", inversedBy="lots")
  * @ORM\JoinColumns({
  *   @ORM\JoinColumn(name="terrain_id", referencedColumnName="id")
  * })
  */
  var $terrain

}

很多

我正在尝试删除地形,但以前我删除了所有与之相关的地块。当我尝试删除地形时,出现错误SQLSTATE[23000]: Integrity constraint violation

最佳答案

删除时,您仍然有从lotsterrain的引用,这就是为什么有Integrity constrait violation的原因。

尝试这个 :

/**
* @ORM\Entity
* @ORM\HasLifecycleCallbacks()
*/
class Terrain
{
    /**
    * @var lots
    *
    * @ORM\OneToMany(targetEntity="Lot", mappedBy="terrain")
    */
    private $lotes;

    /**
    * @ORM\PreRemove
    */
    public function deleteAllLots()
    {
        $lots = $this->getLots();

        foreach ($lots as $lot) {
            $this->lots->removeElement($lot);
            $lot->terrain = null; //$lot->setTerrain(null); will be better, try to add getters and setters
        }
    }
}

如果要从数据库中删除lots,则应使用cascade关系(One-To-Many reference on doctrine-project.com)的OneToMany属性,如下所示:
/**
* @ORM\Entity
* @ORM\HasLifecycleCallbacks()
*/
class Terrain
{
    /**
    * @var lots
    *
    * @ORM\OneToMany(targetEntity="Lot", mappedBy="terrain", cascade={"remove"})
    */
    private $lotes;
}

删除Terrain后,所有批次将被删除。

08-17 04:26