2

I am trying to receive the latest id in a table. Therefore I created a static class to be able to fetch this latest id from any desired table.

public static function getLatestId($entityManager, $table, $column) {
    $qb = $entityManager->createQueryBuilder();
    $qb->select('t.'.$column)->from($table, 't')
       ->orderBy('t.'.$column, 'DESC')->setMaxResults(1);
    $query = $qb->getQuery();
    $result = $query->getSingleResult();
    $latestId = $result[$column];
    return $latestId;
}

When I call the function e.g. with getLatestId($em, 'company', 'companyId') and check the query (with getQuery(), it creates weird statement:

SELECT c0_.companyId AS companyId0 FROM company c0_
ORDER BY c0_.companyId DESC LIMIT 1

Why does it replace the t. by c0_. and suffixes a 0 to the column?

Gottlieb Notschnabel
  • 9,408
  • 18
  • 74
  • 116
  • Maybe using parameters in the `select` clause is possible, at least it seems like that if looking at [another question](http://stackoverflow.com/questions/13689095/how-can-i-pass-a-parameter-to-a-doctrine2-custom-function-in-the-query-builder-s) at Stack Overflow. But I don't get why it doesn't work in my case. – Gottlieb Notschnabel Aug 05 '13 at 09:25

1 Answers1

1

First you are retreiving a partial, which will return a scalar variable by default. So for clarity it's good to use the getSingleScalarResult() method. See also: http://docs.doctrine-project.org/en/latest/reference/partial-objects.html

Then you are trying to read the userId column, but you passed the companyId column. So replace this:

$latestId = $result['userId'];

with this:

$latestId = $result[$column];

Don't worry about the aliases Doctrine gives to your columns. This is normal behaviour and it helps Doctrine to map everything the right way internally.

Flip
  • 4,778
  • 1
  • 34
  • 48