3

I am building a custom repository, and i want to make a selection based on some associations. The problem is that i have a unidirectional association that i do not want to make bidirectional (intentional) and i am selecting the wrong way.

P.S. The reason for not wanting to make it bidirectional is because Bar (in reality user) is used by a lot of entities and i do not want to clog my Bar entity with all those inversed associations.

for example: \Entity\Foo:

namespace Entity;
class Foo
{
    /**
     * @ManyToMany(targetEntity="\Entity\Bar")
     */
    $bars;

    /**
     * @Column(type="string")
     */
    $collection;
}

\Entity\Bar:

namespace Entity;
class Bar
{
}

\Repository\Bar:

namespace Repository;
class Bar
{
    public function findByFooCollection($collection)
    {
        //something needs to go here
    }
}

Should i be writing sql, i would write this query:

SELECT
  *
FROM Bar
INNER JOIN Bar_Foo ON Bar_Foo.bar_id = Bar.id
INNER JOIN Foo on Foo.id = Bar_Foo.foo_id
WHERE Foo.collection = :collection

However as it is DQL or the querybuilder i am using, I get stuck at the association from Bar to Foo.

While giving me an error (logically), this illustrates what i want to do.

$this->getEntityManager()->createQueryBuilder()
                ->select('Bar')
                ->from('Entity\Foo', 'Foo')
                ->innerJoin('Foo.bars', 'Bar')
                ->where('Foo.collection = :collection')
                ->setParameter('collection', $collection);

Is it possible to return a Bar entity from a querybuilder or DQL, filtered on a value of Foo without having to inverse the association?

nvanesch
  • 2,540
  • 14
  • 25
  • 1
    Two ways of doing it are described [in this answer](http://stackoverflow.com/a/15444719) – jkavalik Feb 26 '14 at 07:36
  • Thank you! These are perfect solutions that fit my problem. – nvanesch Feb 26 '14 at 09:09
  • 1
    possible duplicate of [Doctrine 2 DQL - how to select inverse side of unidirectional many-to-many query?](http://stackoverflow.com/questions/5432404/doctrine-2-dql-how-to-select-inverse-side-of-unidirectional-many-to-many-query) – nvanesch Apr 03 '14 at 08:04

0 Answers0