在我的模板中,我想调用一个函数来显示公司中员工的总数。员工与部门,部门相关的部门与一对多关系有关。
{% 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的company.class中来实现这一点
另一个问题是,如何正确使用Doctrine或DQL来查询多个Join? 我试过这个功能,但我不知道这是不是正确的方法
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 ?>
任何想法?
答案 0 :(得分:3)
只需创建一个枝条扩展,并与参数一起使用;类似的东西:
扩展类:
$this->output->set_header('Content-Type: text/html; charset=utf-8');
在service.yml中定义您的扩展并注入实体管理器:
<?php
namespace WHERE\YOU_WANT\TO\CREATE_IT;
class TestExtension extends \Twig_Extension
{
protected $em;
public function __construct($em)
{
$this->em = $em;
}
public function getFunctions()
{
return array(
//this is the name of the function you will use in twig
new \Twig_SimpleFunction('number_employees', array($this, 'a'))
);
}
public function getName()
{
return 'nbr_employees';
}
public function a($id)
{
$qb=$this->em->createQueryBuilder();
$qb->select('count(n.id)')
->from('XYZYOurBundle:Employee','n')
->where('n.company = :x)
->setParameter('x',$id);
$count = $qb->getQuery()->getSingleScalarResult();
return $count;
}
}
最后你可以在你的模板中使用它,如:
numberemployees:
class: THE\EXTENSION\NAMESPACE\TestExtension
tags:
- { name: twig.extension }
arguments:
em: "@doctrine.orm.entity_manager"