【问题标题】:Handshake between ManyToMany relation created by Symfony's make:entity commandSymfony 的 make:entity 命令创建的 ManyToMany 关系之间的握手
【发布时间】:2021-09-26 17:54:08
【问题描述】:

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

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

举例说明:

假设你有这两个类:

  • 语言
  • 国家
# Now running:
bin/console make:entity Country

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

这些步骤将在Country 类中生成以下代码:

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

Language 课程中,你会得到这个:

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

我试图理解为什么Language$country->addLanguage($this);Country 没有。

【问题讨论】:

  • 想想如果这样做会发生什么。或者试试看。
  • @Cerad 如果你猜是因为递归,我不认为是因为!$this->countries->contains($country)
  • 这有助于@Cerad,谢谢!
  • @Cerad 根据 maker 命令,文档有点混乱。文档说ArticleTag 的所有者,所以Articleinverse sideTagmap side。文档说:$tag->addArticle($this); // synchronously updating inverse sideTag 不是inverse side。看这里可以更好地理解:symfonycasts.com/screencast/doctrine-relations/many-to-many。因此,这一切对我帮助很大。谢谢!

标签: php symfony symfony4 php-7


【解决方案1】:

这是正确答案:

请记住,所有这些拥有与反向的东西都很重要,因为当 Doctrine 保存一个实体时,它只查看关系的拥有方来确定要保存到数据库的内容。所以,如果我们给一篇文章添加标签,Doctrine 会正确地保存它。但是,如果您将文章添加到标签并保存,Doctrine 将无能为力。好吧,在实践中,如果你使用 make:entity,那是不正确的。为什么?因为生成的代码会同步拥有方。如果你在里面调用$tag->addArticle(),那就调用$article->addTag()

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-18
    • 2016-11-25
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多