期望一个或者没有来自学说查询构建器的结果,我应该使用什么?

Fae*_*ery 28 php symfony doctrine-orm

我有这个方法:

public function getMonth ($month_name)
    {
        $q = $this->createQueryBuilder('m');

        $q->select('m')
            ->where('m.name = :name')    
            ->setParameter('name', $month_name);

        return $q->getQuery()->getResult();
    }
Run Code Online (Sandbox Code Playgroud)

从中我希望找到一个月或0个月.我在控制器中以这种方式使用此方法:

$month = $em->getRepository('EMExpensesBundle:Month')
                ->getMonth($this->findMonth());

            $month->setSpended($item->getPrice());
Run Code Online (Sandbox Code Playgroud)

我尝试了这getSingleResult()一切,一切都很完美,直到我遇到一个没有找到月份的情况,一切都失败了!

然后我尝试了getResult(),但它返回一个数组,然后

$month->setSpended($item->getPrice());
Run Code Online (Sandbox Code Playgroud)

据说被称为非对象并修复它我应该到处使用

$month[0]->setSpended($item->getPrice());
Run Code Online (Sandbox Code Playgroud)

是否有更优雅的方法来实现这一点,而无需在任何地方添加不必要的[0]索引?

小智 65

另外,在Doctrine 2.1中你可以使用'getOneOrNullResult'

http://doctrine-orm.readthedocs.org/en/latest/reference/dql-doctrine-query-language.html#query-result-formats

  • 要小心,如果有多个结果,则只返回异常.不是空值.https://coderwall.com/p/prbrlw/doctrine-get-single-row-or-null:无结果:返回null //多个结果:抛出一个NonUniqueResultException异常 (6认同)

Sgo*_*kes 33

如果您使用getSingleResult,Doctrine会抛出一个\Doctrine\ORM\NoResultException,您可以捕获并处理它.如果你想直接在Repository中捕获它,我会建议:

public function getMonth ($month_name)
{
    $q = $this->createQueryBuilder('m');

    $q->select('m')
        ->where('m.name = :name')    
        ->setParameter('name', $month_name);

    try {
        return $q->getQuery()->getResult(); 
        }
    catch(\Doctrine\ORM\NoResultException $e) {
        return new Month();
    }
}
Run Code Online (Sandbox Code Playgroud)

别忘了添加一个use Your\Namespace\Month;或这将失败,因为它找不到Month类!

当然,如果它是一个新实体,你还必须坚持实体.您可以像这样扩展catch块:

catch(\Doctrine\ORM\NoResultException $e) {
    $month = new Month();
    $this->_em->perist($month);

    return $month;
}
Run Code Online (Sandbox Code Playgroud)

您还可以在控制器中捕获异常,使其更加透明.但这取决于您的使用案例,最好由您自己解决