Fabian
Fabian

Reputation: 1836

Symfony2 - How to fetch/join only related entities with a certain condition (one-to-many relation)?

I have a onetomany relationship between event and participant entities. In my controller i can do the following:

$participants = $event->getParticipant();

But now i only want the Participants where the property visible has the value 1.

how can i get those collection? because participant is an arraycollection of all participants with participant.event_id = event.id in the event entity.

Upvotes: 1

Views: 852

Answers (1)

Nicolai Fröhlich
Nicolai Fröhlich

Reputation: 52493

You can easily create a method in your EventRepository that joins only the visible participants with the event:

// YourBundle/Entity/EventRepository.php

public function getEventFilterVisibleParticipants($event_id)
{
    return $repository->createQueryBuilder('event')
        ->where('event.id = :event_id')
        ->leftJoin('event.participants', 'participant', 'WITH', 'participant.visible = :visibility')
        ->setParameter('event_id', $event_id)
        ->setParameter('visibility', 1)
        ->orderBy('event.startDate', 'DESC')
        ->getQuery()
        ->getResult()
    ;
}

... Now in your controller do something like this:

$event = $this
    ->getDoctrine()
    ->getRepository('YourBundle:Event')
    ->getEventFilterVisibleParticipants($id)
;

$participants = $event->getParticipants(); // returns the filtered collection

Upvotes: 1

Related Questions