1
votes

I have a question about left join in doctrine in Symfony 2.7.

Example code:

public function test($id, $offset, $limit)
{
    $build = $this->createQueryBuilder('building');
    $build
        ->addSelect('users', 'numbers')
        ->join('building.users', 'users')
        // limit the numbers for 1 result!
        ->leftJoin('building.numbers', 'numbers') // only select 1 result instead of more.
        ->where('building.id = :id')
        ->setParameter('id', $id);

    $paginator = new Paginator($build->getQuery(), $fetchJoinCollection = true);
    $result = $paginator->getQuery()
        ->setFirstResult($offset)
        ->setMaxResults($limit)
        ->getResult();

    return $result;
}

My question now is how could we implement that the ->leftJoin('building.numbers', 'numbers') only return MAX 1 result.

Thanks!

Doctrine orm: 2.2.3, Symfony version: 2.7

1
What do you mean by "select 1 result instead of more"? Any entry from numbers would do or is there any kind of order that should be taken into account? - Alan T.
I would like to limit the results from numbers to 1. @AlanT. - Car
So any entry from numbers would be ok, you just want to limit the result set to a single entry? - Alan T.
Yes that is oke, want only single entry @AlanT. - Car
What kind of association is it? ManyToOne owned by a Number entity? - Alan T.

1 Answers

0
votes

If you do not really care what specific number you retrieve and only want to get a single one, you could use a GROUP BY clause using the column owning the association between your buildings and your numbers. A basic query builder allowing to do that would look like this:

$qb = $this->createQueryBuilder('building')
    ->addSelect('numbers')
    ->leftJoin('building.numbers', 'numbers')
    ->groupBy('numbers.building');

Note: If you use the default hydration mode and retrieve objects, your numbers collections will only have a single entry (or none) even if there are more in reality. This could produce some problems if you try to perform updates based on those partially hydrated collections.