【问题标题】:How to take the smallest id of a table with Doctrine?如何使用 Doctrine 获取表格的最小 id?
【发布时间】:2018-04-05 08:12:58
【问题描述】:

我想方设法取一个城市的最小 id 以避免我的一元论测试中的错误。尝试后,我有这个错误:

Doctrine\ORM\Query\QueryException: [语法错误] 第 0 行,第 62 列:

错误:预期 =、、>、>=、!=、得到 'AS'

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

【问题讨论】:

    标签: php symfony doctrine-orm doctrine dql


    【解决方案1】:

    你可以试试这个:

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

    您也可以使用getSingleScalarResult 代替getResult 来仅获得一个标量结果

    【讨论】:

    • 很高兴帮助你@Paul
    • 使用getSingleScalarResult()来避免数组结果?
    • 是的,这可能是一个好习惯,我使用了 getResult,因为 OP 使用了该功能
    【解决方案2】:
    $qb = $this->getEntityManager()->createQueryBuilder();
    $id = $qb
        ->select('MIN(city.id) AS id')
        ->from('AppBundle:City', 'city');
    

    【讨论】:

    • 尽管此代码可能(或可能不会)解决问题,但一个好的答案总是需要解释它如何/为什么会有所帮助。
    • 我同意你的观点,但这里只是扣除了一点零钱。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 2016-04-14
    • 1970-01-01
    • 2021-09-24
    • 2018-07-12
    • 1970-01-01
    相关资源
    最近更新 更多