Symfony:PropertyAccessor 问题

Symfony : issue with PropertyAccessor

我的 属性Accessor 有问题:有以下两个实体:

class Foo
{

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Bar", inversedBy="foo")
     * @ORM\JoinColumn(nullable=false)
     */
    private $bar;

    public function getBar(): ?Bar
    {
        return $this->bar;
    }

    public function setBar(?Bar $bar): self
    {
        $this->bar = $bar;
        return $this;
    }
}


class Bar
{
    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Foo", mappedBy="bar", orphanRemoval=true, cascade="all")
     */
    private $foo

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

    /**
     * @return Collection|Foo[]
     */
    public function getFoo(): Collection
    {
        return $this->foo;
    }

    public function addFoo(Foo $foo): self
    {
        if (!$this->foo->contains($foo)) {
            $this->foo[] = $foo;
            $foo->setBar($this);
        }
        return $this;
    }

    public function removeFoo(Foo $foo): self
    {
        if ($this->foo->contains($foo)) {
            $this->foo->removeElement($foo);
            // set the owning side to null (unless already changed)
            if ($foo->getBar() === $this) {
                $foo->setBar(null);
            }
        }
        return $this;
    }

}

我有很多集合,例如 Foo,所以我使用 属性 访问器以编程方式访问它们。但是当我做一个 :

            $bar = new Bar();
            $foo = new Foo();
            $propertyAccessor->getValue($bar, 'foo')->add($foo);

$foo->bar 保持为空。

正常吗?

那么移除孤儿是否仍然有效?

感谢您的帮助

是的,这是预期的。

$propertyAccessor->getValue($bar, 'foo') 将 return ArrayCollection 的实例。在集合上调用 add($foo),不会神奇地设置 $foo->bar。我猜你在 Bar.

上把它和 addFoo() 搞混了

关于您的第二个问题:调用 $bar->removeFoo($anyFoo) 将触发删除数据库中的 $anyFoo 表示。

setValue方法支持添加到集合中。您应该直接为 $bar.

调用此方法
$propertyAccessor->setValue($bar, 'foo', [$foo]);

有关详细信息,请参阅 documentation