【问题标题】:symfony2 twig render, exception thrownsymfony2 树枝渲染,抛出异常
【发布时间】:2023-12-27 13:03:01
【问题描述】:

所以在我的基本模板中,我有:{% render "EcsCrmBundle:Module:checkClock" %}

然后我创建了 ModuleController.php...

<?php

namespace Ecs\CrmBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Ecs\CrmBundle\Entity\TimeClock;

class ModuleController extends Controller
{
    public function checkClockAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $user = $this->get('security.context')->getToken()->getUser();
        $today = time();
        $start = date('Y-m-d 00:00:00');
        $entities = $em->getRepository('EcsCrmBundle:TimeClock');
        $query = $entities->createQueryBuilder('tc')
                ->select('tc.in1, tc.out1, tc.in2, tc.out2, tc.in3, tc.out3')
                ->where('tc.noteBy = :user')
                ->andWhere('tc.daydate >= :start')
                ->setParameter('user', $user->getid())
                ->setParameter('start', $start)
                ->setMaxResults('1')
                ->getQuery();
         $entities = $query->getSingleResult();
         if (empty($entities)) {
            $ents = "clocked_out";
            $this->get('session')->set('clockedin', 'clocked_out');
         } else {
            for ($i=1; $i <= 3; $i++) {
                if ($entities["in$i"] != NULL) {
                    $ents = "clocked_in";
                    if ($i == 1) {
                        $this->get('session')->set('nextclock', "out$i");
                    } else {
                        $x = $i+1;
                        $this->get('session')->set('nextClock', "out$x");
                    }
                    if ($entities["out$i"] != NULL) {
                        $ents = "clocked_out";
                        $x = $i+1;
                        $this->get('session')->set('nextclock', "in$x");
                    }
                    if ($entities["out3"] != NULL) {
                        $ents = "day_done";
                    }
                }
            }
         }
        return $this->render('EcsCrmBundle:Module:topclock.html.twig', array(
            'cstat' => $ents,
        ));
    }
}

问题是,如果特定用户在特定日期的数据库中没有任何内容..我不断得到:

An exception has been thrown during the rendering of a template ("No result was found for query although at least one row was expected.") in ::base.html.twig at line 161.
500 Internal Server Error - Twig_Error_Runtime
1 linked Exception: NoResultException »

我知道这与数据库没有“结果”这一事实有关......但这不是我通过拥有if (empty($entities)) { 所完成的吗?我不知道修复它...任何帮助表示赞赏...

【问题讨论】:

    标签: symfony twig


    【解决方案1】:

    替换:

    $entities = $query->getSingleResult();
    

    $entity = $query->getOneOrNullResult();
    

    如果您查看 Doctrine\ORM\AbstractQuery,您会看到 getSingleResult 需要一个且只有一个结果。 0 将通过异常。

    我更仔细地查看了您的代码,看起来您实际上期望的是一组实体。在这种情况下使用:

    $entities = $query->getResult();
    

    【讨论】:

    • 不错!我正在处理一个类似这样的问题,而你为我解决了它.. +1 为 OP 和 +1 为 Cerad!