Search code examples
phpsymfonysymfony4php-7

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


So, can you please clarify to me why the Symfony's command make:entity generates different addProperty methods to a ManyToMany relation?

I spent a few minutes trying to understand why and didn't get yet.

To Exemplify:

Assuming you have these two classes:

  • Language
  • Country
# Now running:
bin/console make:entity Country

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

These steps will generate the following code in Country class:

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

In the Language class you'll get this:

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

I'm trying to understand why Language has the line $country->addLanguage($this); and Country doesn't have.


Solution

  • This is the correct answer:

    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()

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