简体   繁体   English

教义2-多对多加入

[英]Doctrine 2 - many to many join

I have two entities in many to many relation: 我在多对多关系中有两个实体:

class Foo
{
    /**
     * @ORM\ManyToMany(targetEntity="Bar", inversedBy="foos")
     * @ORM\JoinTable(name="Foo_x_Bar")
     */
    protected $bars;
}

class Bar
{
    /**
     * @ORM\ManyToMany(targetEntity="Foo", mappedBy="bars")
     */
    protected $foos;
}

I would like to fetch all pairs of Foo and Bar instances in a result set ie: 我想在结果集中获取所有的Foo和Bar实例对,即:

array (size=2)
  0 => 
    array (size=2)
        'Foo' => Foo instance
        'Bar' => Bar instance
  1 => 
    array (size=2)
        'Foo' => Foo instance
        'Bar' => Bar instance

I tried to do it in a several ways described on the web but I still can't select the whole entities. 我试图通过网络上介绍的几种方法来做到这一点,但仍然无法选择整个实体。 I am able to get particular columns with this query: 我可以通过此查询获取特定的列:

SELECT f.something, b.somethingElse FROM Entity\\Foo f LEFT JOIN f.bars b

but when I omit column names in SELECT statement I only get Foo instances and Bar instances disappears. 但是当我在SELECT语句中省略列名时,我只会得到Foo实例,而Bar实例会消失。 How can I get a result set containing both entities? 如何获得包含两个实体的结果集?

The ManyToMany relation is really quite limited in Doctrine 2. It's all generated automatically and it's not an entity. 在Doctrine 2中,ManyToMany关系确实非常有限。它都是自动生成的,不是实体。

If you want to go beyond the basic default behavior then create yourself a FooBar entity and setup individual ManyToOne relations with Foo and Bar. 如果您想超越基本的默认行为,则可以为自己创建一个FooBar实体,并与Foo和Bar建立单独的ManyToOne关系。

Doing so will allow you to query directly on FooBar. 这样做将使您可以直接在FooBar上进行查询。 It also allows you to add additional properties/relations to your join tables. 它还允许您向联接表添加其他属性/关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM