Chris Tickner
Chris Tickner

Reputation: 2017

Doctrine Query Builder - How to select a many-to-many relationship?

I have a form in Symfony2 that needs to have an entity choice field filled with a collection of Players in a particular tournament. I create the form Type and pass the tournament ID to the query_builder property of the correct field. In the entity repository I have this method:

public function allPlayersInTournamentQuery($tournament_id)
{
    $repo = $this->getEntityManager()->getRepository('GameBundle:Tournament');
    $tournament = $repo->find($tournament_id);
    $players = $tournament->getPlayers();
    $playersIds = array();
    foreach ($players as $player) {
        $playersIds[] = $player->getId();
    }
    $playersQuery = $this->createQueryBuilder('p')
        ->in('p.id', $playersIds)
        ->orderBy('p.real_name', 'ASC');
    return $playersQuery;
}

The function in() does not exist in the query builder. I hope the method shows what I am trying to do. Im tying to return the query builder that selects the correct players found in the given tournament.

How can I achieve this?

Thanks!

Upvotes: 4

Views: 2855

Answers (1)

Reuven
Reuven

Reputation: 3336

You can use the helper methods provided by the query builder $playersQuery->expr()->in('p.id', $playersIds)

Your query will be something like that:

$playersQuery = $this->createQueryBuilder('p');
$playersQuery->where($playersQuery->expr()->in('p.id', $playersIds))
             ->orderBy('p.real_name', 'ASC');

More information about the helper methods here

Upvotes: 3

Related Questions