1

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

Car
  • 13
  • 6

1 Answers1

0

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.

Alan T.
  • 1,382
  • 1
  • 7
  • 14
  • Grouping error: 7 ERROR: column "b0_.start_date" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: SELECT CASE WHEN b0_.start_date IS NULL THEN b0_.created_d... – Car Feb 07 '18 at 13:02
  • This was the error getting when using it in combine with the other problem you helped me solve. You know any idea how to fix this? – Car Feb 07 '18 at 13:03