Doctrine joins many many without association

I have: two objects with unidirectional association M: M.

class ShareInfo { // ... /** * @ORM\ManyToMany(targetEntity="Item") * @ORM\JoinTable(name="share_info_items", * joinColumns={@ORM\JoinColumn(name="share_id", referencedColumnName="id")}, * inverseJoinColumns={@ORM\JoinColumn(name="item_id", referencedColumnName="id")}) * * @var Item[] */ private $items; } class Item { // ... // This entity has no association with ShareInfo, // because M:M is undirectional and defined in ShareInfo entity } 

What I want: Select the data from the element table (object object) where at least one M: M record exists between Item and ShareInfo.

My suggestion that does not work (I have a semantic error) :

 $queryBuilder ->select('i') ->from(Item::class, 'i') ->innerJoin(ShareInfo::class, 'shareInfo', 'WITH', 'shareInfo.items = i'); 

In pure SQL, I would do something like this:

 SELECT i.* FROM items i INNER JOIN share_info_items shareInfo ON shareInfo.item_id = i.id 

I can’t believe that there is no DQL analogue for this. The only solution I can imagine is to split the undirected association M: M into bidirectional

PS This question has no duplicates, I checked it well.

+6
source share
1 answer

The way to achieve this is through a subquery:

 $em=$this->getDoctrine()->getManager(); $queryBuilder1=$em->createQueryBuilder(); $queryBuilder1->select(array('DISTINCT i.id')) ->from('AppBundle:ShareInfo', 'share_info') ->innerJoin('share_info.items', 'i'); $queryBuilder=$em->createQueryBuilder(); $queryBuilder->select('i') ->from('AppBundle:items', 'i') ->where($queryBuilder->expr() ->in('i.id',$queryBuilder1->getDql())); 
-1
source

Source: https://habr.com/ru/post/986603/


All Articles