如何用 Doctrine 取 a table 的最小 id?

How to take the smallest id of a table with Doctrine?

我正在寻找一种方法来获取城市的最小id,以避免在我的一元论测试中出错。尝试后,我有这个错误:

Doctrine\ORM\Query\QueryException: [Syntax Error] line 0, col 62:

Error: Expected =, <, <=, <>, >, >=, !=, got 'AS'

public function testDB()
{
    $id = $this->entityManager
        ->getRepository('AppBundle:City')
        ->createQueryBuilder('b')
        ->where("MIN(b.id) AS id")
        ->getQuery()
        ->getResult();
}

你可以试试这个:

$qb = $this->getEntityManager()->createQueryBuilder();
$id = $qb
        ->select('city.id')
        ->from('AppBundle:City', 'city')
        ->orderBy('city.id', 'ASC')
        ->setMaxResults(1)
        ->getQuery()
        ->getResult();

如果 getResult 只得到一个标量结果,您也可以使用 getSingleScalarResult 代替

$qb = $this->getEntityManager()->createQueryBuilder();
$id = $qb
    ->select('MIN(city.id) AS id')
    ->from('AppBundle:City', 'city');