【发布时间】:2015-11-26 05:21:14
【问题描述】:
我在教义上有一对多的关系。我想计算每个相关字段并在 Twig for 循环中显示它们
到目前为止
Vp 与 Voters 相关。Vp 有很多 Voters,Voters 有一个 Vp 我想计算每个 Vp 的每个相关选民
public function getAllVp()
{
return $this
->createQueryBuilder('v')
->select('vp.id,COUNT(v.id) as num')
->from('Voters', 'v')
->join('v.Vp', 'vp')
->orderBy('v.id', 'ASC')
->getQuery()
->getResult()
;
}
我想在 Twig 中这样使用
{% for vp in vps %}
{{ vp.firstname }}
{{ vp.num }}//number of voters
{% endfor %}
控制器
$vice_president = $em->getRepository('Bundle:Vp')->getAllVp();
return $this->render('Bundle:Vp:all_vp.html.twig', array(
'vps' => $vice_president,
));
教义
fields:
firstname:
type: string
length: 255
lastname:
type: string
length: 255
photo:
type: string
length: 255
oneToMany:
voters:
targetEntity: Voters
mappedBy: vp
我收到了这个错误
[Semantical Error] line 0, col 94 near 'vp, Voters v': Error: Class Project\Bundle\DuterteBundle\Entity\Vp 没有名为 Vp 的关联
如何在 Doctrine 中正确实现这一点?
更新
voters.orm.yml
manyToOne:
vp:
targetEntity: Vp
cascade: { }
mappedBy: null
inversedBy: voters
joinColumn:
name: vp_id
referencedColumnName: id
orphanRemoval: false
我可以通过简单地调用相关的'voters'并在 Twig 中添加一个过滤器来实现这一点。但我的目的是计算学说中的数据,在其他模板中重用它或将其转换为 json 以供将来使用,例如在 Angular 中JS
{% if vp.voters|length > 0 %}
<tr {% if loop.index is odd %}class="color"{% endif %}>
<td>{{ vp.id }}</td>
<td>{{ vp.getFullName() }}</td>
<td>{{ vp.voters|length|number_format }}</td>
</tr>
{% endif %}
上面是一个工作代码,但我想在 Doctrine 中进行计数,而不是在模板中
预期结果
id fullname counts
1 George Bush 45
2 ali gail 1999
4 Mae Young 45
......
【问题讨论】:
-
拜托,你能发布选民实体的学说映射吗?
-
@Delphine 我会更新我的问题。
标签: symfony doctrine-orm twig