在我的模板中,我想調用一個函數來顯示公司中員工的總數。員工與公司相關的部門,部門在一對多關係。在哪裏創建Symfony 2模板中使用的方法
{% for com in company %}
{{ com.name }}
{{ com.description }}
{{ com.getNumberOfEmp|length }} //this a function must display counts of employee
{% endfor %}
在控制器
$em = $this->getDoctrine()->getManager();
$company = $em->getRepository('Bundle:Company')->findAll();
我應該在哪裏把getNumberOfEmp方法?
在Symfony的1.4,我很容易把getNumberOfEmp在將調用company.table.class
的另一個問題是,如何正確使用Doctrine或DQL查詢多個加入company.class實現這一點? 我試過這個功能,但我不知道這是否是正確的方法
companyrepository.php
public function getNumberOfEmp()
{
return $this
->createQueryBuilder()
->select('e.firstname')
->from('Emp e')
->leftJoin('e.Department d')
->leftJoin('d.Company c')
->where('i.id =:$id)
->setParameter('id',$this->id)// I am confused about this since i want to display all names of the company
->getQuery()
->getResult()
;
}
在Symfony的1.4我使用這種方式
//company.class.php
public function getNumberOfEmp()
{
$emp = Doctrine_Core::getTable('Company')->createQuery('c')
->select('v.firstname')
->from('Employeers e')
->leftJoin('e.Department d')
->leftJoin('d.Company c')
->where('c.id=?',$this->id);
return $emp->execute();
}
,輕鬆地把它稱爲PHP模板
<?php foreach ($company as $com): ?>
<?php echo $com->name ?>/display name of company
<?php echo $com->description ?>//description
<?php echo count($com.getNumberOfEmp) ?>//dispalys number of employees
<?php endforeach ?>
任何想法?
一個帖子中有兩個問題。很少有好消息的預兆。對於你的第一個問題,看看樹枝擴展:http://symfony.com/doc/current/cookbook/templating/twig_extension.html – Cerad
對於你的第二個問題,你的連接看起來不錯,但看看這裏:http:/ /stackoverflow.com/questions/9214471/count-rows-in-doctrine-querybuilder/9215880#9215880因爲所有你需要的是一個計數。 – Cerad