【问题标题】:Doctrine ManyToMany with referencedColumnName具有引用列名的多对多原则
【发布时间】:2019-10-24 10:52:47
【问题描述】:

我有两个具有多对多关系的模型。 ID 不由原则管理,而是由来自不同应用程序的 GUID 生成器管理。所以我的实体有一个名为uniqueIdentifier 而不是id 的字段。这样做:

class Bar {
    /**
    * @ManyToMany(targetEntity="Foo", mappedBy="bar")
    */
    private $foo;

}

class Foo {
    /**
    * @ManyToMany(targetEntity="Bar", mappedBy="foo")
    */
    private $bar;

}

我收到一条错误消息,指出 Column name 'id' referenced for relation from App\Entity\Foo towards App\Entity\Bar does not exist。我知道这是由于将内容映射到 _id 的引用列名和连接表的 table1_table2 的学说默认值。

我无法覆盖默认值,因为一些模型确实具有自动生成的值并依赖于id 字段。相反,我想做如下的事情:

class Bar {
    /**
    * @ManyToMany(targetEntity="Foo", mappedBy="bar")
    * @JoinColumn(name="foo_uid", referencedColumnName="uniqueIdentifier")
    */
    private $foo;

}

class Foo {
    /**
    * @ManyToMany(targetEntity="Bar", mappedBy="foo")
    * @JoinColumn(name="bar_uid", referencedColumnName="uniqueIdentifier")
    */
    private $bar;

}

这不起作用,我得到同样的错误。怎么办?

【问题讨论】:

    标签: php database doctrine-orm doctrine


    【解决方案1】:

    您的关联映射应该是这样的:

    class Bar
    {
        /**
         * @var Foo[]|\Doctrine\Common\Collections\Collection
         *
         * @ORM\ManyToMany(targetEntity="Foo", inversedBy="bar")
         * @ORM\JoinTable(
         *     name="table1_table2",
         *     joinColumns={
         *          @ORM\JoinColumn(name="foo_uid", referencedColumnName="uniqueIdentifier")
         *     },
         *     inverseJoinColumns={
         *          @ORM\JoinColumn(name="bar_uid", referencedColumnName="uniqueIdentifier")
         *     }
         * )
         */
        private $foo;
    }
    
    class Foo {
        /**
         * @var Bar[]|\Doctrine\Common\Collections\Collection 
         * 
         * @ORM\ManyToMany(targetEntity="Bar", mappedBy="foo")
         */
        private $bar;
    }
    

    记住foo_uidbar_uid 列将在table1_table2 表中,uniqueIdentifier 是 Foo 和 Bar 表上的标识符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-29
      • 1970-01-01
      • 2023-03-08
      • 2023-03-31
      • 2022-01-18
      • 2015-04-05
      • 1970-01-01
      相关资源
      最近更新 更多