0

例如,我有两个实体:

class Dog
{

    /**
     * @var House
     *
     * @ORM\ManyToOne(targetEntity="House")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="house_id", referencedColumnName="id")
     * })
     */
    private $house;
}

class House
{

     /**
     * @var ArrayCollection|null
     * @ORM\ManyToMany(targetEntity="Dog",cascade={"persist"})
     * @ORM\JoinColumns({
     * @ORM\JoinColumn(name="dog_id", referencedColumnName="id", nullable=true)
     * })
     */
    protected $dog;
}

house如果Entity中的字段Dog被更新(设置或删除),我需要抛出一个事件,然后在 Entity House 中添加或删除字段 dog。谁能告诉我如何做到这一点?

4

2 回答 2

0

你必须调用 $dog->setHouse($this); 来自 addDog 方法。如果您使用命令行,则会为您生成下面的 House 类。

class House
{
    // ...

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Dog", mappedBy="house")
     */
    private $dogs;

    public function __construct()
    {
        $this->dogs = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    /**
     * @return Collection|Dog[]
     */
    public function getDogs(): Collection
    {
        return $this->dogs;
    }

    public function addDog(Dog $dog): self
    {
        if (!$this->dogs->contains($dog)) {
            $this->dogs[] = $dog;
            $dog->setHouse($this);       // <-- here you go
        }

        return $this;
    }

    public function removeDog(Dog $dog): self
    {
        if ($this->dogs->contains($dog)) {
            $this->dogs->removeElement($dog);
            // set the owning side to null (unless already changed)
            if ($dog->getHouse() === $this) {
                $dog->setHouse(null);
            }
        }

        return $this;
    }
}

removeDog() 方法同样重要。

于 2019-12-22T14:08:42.090 回答
0

Doctrine 将为您执行此操作,但取决于级联选项。但是您的注释不正确。在 Dog 实体中,您有一个 ManyToOne 的注释,而在 House 实体中有一个 ManyToMany 关系的注释。但你应该选择

  1. 多对一 - 一对多
  2. 多对多 - 多对多

查看 Doctrine 的关联映射以了解所有类型的关联以及如何定义它们。

如果您使用 Symfony(4 或 5),您应该使用命令行 make 工具添加带有所有注释的属性和方法,即使是关系。

bin/console make:entity Dog

relation在询问字段类型时键入,您将不得不回答一些其他问题。

于 2019-12-21T18:36:31.000 回答