Symfony 的 make:entity 命令创建的 ManyToMany 关系之间的握手

Handshake between ManyToMany relation created by Symfony's make:entity command

那么,您能否向我解释一下为什么 Symfony 的命令 make:entity 会为 ManyToMany 关系生成不同的 addProperty 方法?

我花了几分钟试图理解原因,但还没有理解。

举例说明:

假设你有这两个 classes:

# Now running:
bin/console make:entity Country

# You'll enter in the interactive terminal, just type:
> languages
> ManyToMany
> Language
> yes

这些步骤将在Countryclass中生成如下代码:

    ...
    public function addLanguage(Language $language): self
    {
        if (!$this->languages->contains($language)) {
            $this->languages[] = $language;
        }
        return $this;
    }
    ...

Language class 你会得到这个:

    ...
    public function addCountry(Country $country): self
    {
        if (!$this->countries->contains($country)) {
            $this->countries[] = $country;
            $country->addLanguage($this);
        }
        return $this;
    }
    ...

我想了解为什么 Language 有行 $country->addLanguage($this);Country 没有。

这是正确答案:

Remember, all of this owning versus inverse stuff is important because, when Doctrine saves an entity, it only looks at the owning side of the relationship to figure out what to save to the database. So, if we add tags to an article, Doctrine will save that correctly. But, if you added articles to a tag and save, Doctrine would do nothing. Well, in practice, if you use make:entity, that's not true. Why? Because the generated code synchronizes the owning side. If you call $tag->addArticle(), inside, that calls $article->addTag()

来源:https://symfonycasts.com/screencast/doctrine-relations/many-to-many