Twig模板内的异常处理

Dr *_*eto 5 exception relation symfony twig

我是symfony2的新手。我的项目有两个实体

    [1] Category and
    [2] Evaluation
Run Code Online (Sandbox Code Playgroud)

并且类别有很多评估,所以问题是当我删除类别然后显示评估然后显示错误

"An exception has been thrown during the rendering of a template ("Entity was not found.") in HfAppBundle:SpecificEvaluations:index.html.twig at line 137. "

在137行上是内容{{evaluation.category.name}}。我也尝试过

    {% if evaluation.category.name is not null %}
        {{evaluation.category.name}}
    {% endif %}
Run Code Online (Sandbox Code Playgroud)

但这也给我同样的错误。有人可以帮忙吗?

谢谢

Pra*_*esh 0

检查与评估关联的类别是否存在,而不是检查类别名称。

{% if evaluation.getCategory  %}
        {{evaluation.category.name}}
{% endif %}
Run Code Online (Sandbox Code Playgroud)

理想情况下,当您删除链接到多个评估的类别时,您应该删除已删除的类别与评估之间的关系。

为此,指定删除类别时是删除所有评估还是在删除类别时将所有相关评估的类别设置为空。为此,在 yml 中,关系应定义为

manyToOne:
        user:
          targetEntity: LB\CoreBundle\Entity\User
          joinColumn:
            name: user_id
            referencedColumnName: id
            onDelete: "SET NULL"
Run Code Online (Sandbox Code Playgroud)

onDelete 可以是“SET NULL”或“CASCADE”,具体取决于您是否需要将评估时的类别字段设置为空或删除与类别相关的所有评估。

修改您的代码以设置评估类别,如下所示。将类别设置为空后,您没有保留评估。

$evaluations = $em->getRepository('HfAppBundle:Evaluation')->findByCategory($catId); 

foreach ($evaluations as $evl) { 
$evl->setCategory(null);
//this line was missing
 $em->persist($evl);
} 

$em->flush(); 
Run Code Online (Sandbox Code Playgroud)