【发布时间】:2012-10-19 14:54:23
【问题描述】:
假设我有一个 Category 实体,一个 Person 实体,这两个实体通过 Contract Entity 相关联。
在我看来,我需要显示一个类别及其所有子类别和人数
例如: 当用户在页面上查看“A 类”时,我希望他/她看到:
Category A 10 persons
subcategory a.1 4 persons
subcategory a.2 6 persons
所以在我的 show.html.twig 中,我会写:
{{ category.title }} {{ nb_persons }}
{% for child in children %}
{{ child.title }} //{{ child.getNbPersons() }}??, how to get the number of persons for each child ?
{% endfor %}
这是我的 CategoryController.php
public function showAction($id_category)
{
$em=$this->getDoctrine()->getEntityManager();
$repo = $em->getRepository('MyBundle:Category');
$this->param['category']= $repo->find($id);
$this->param['nb_persons'] = $repo->getNbPersonsByCategory($id_category);
$this->param['children'] = $repo->children($this->param['category'], true, 'title');
return $this->render('MyBundle:Category:show.html.twig', $this->param);
}
但是要显示每个子类别(孩子)的人数,我需要使用 child.getNbPersons() 之类的方法,但这会迫使我在我的实体 Category.php 中使用存储库函数,这很糟糕练习我认为。 我能做些什么 ?
【问题讨论】:
-
我不认为实体存储库方法是一个不好的做法。它们在这种情况下非常有用。
-
感谢您的回答,所以我需要访问容器以在我的实体 Category.php 中获取实体管理器,我尝试了这个 $em=$this->container->get('doctrine' )->getEntityManager();但容器似乎没有在这里定义..我怎么能访问它?
标签: php model-view-controller symfony tree twig