Symfony2 Twig 获取子实体的总数 [英] Symfony2 Twig Get Total Count for Child Entity

查看:24
本文介绍了Symfony2 Twig 获取子实体的总数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

存在以下实体:农场、谷仓和动物.一个农场可以有很多谷仓,一个谷仓可以有很多动物.

The following entities exist, Farm, Barn and Animals. A Farm can have many Barns and a Barn many Animals.

在 TWIG 模板中显示农场时,还应显示动物数量.

When displaying a Farm in a TWIG template the number of Animals should be shown as well.

最好的方法是什么?

我创建了一个 TWIG 扩展,它可以让我轻松显示谷仓的数量.

I have create a TWIG extension which allows me to easily show the number of barns.

public function totalFieldFilter($data, $getField='getTotal') {
    $total = count($data->$getField());
    return $total;
}

在我的模板中,我将使用 {{ farm|totalField('getBarns') }},我可以轻松地扩展它来编写另一个自定义函数,如下所示:

In my template I would use {{ farm|totalField('getBarns') }}, I could easily extend this to write another custom function like so:

public function totalFieldFilter($farm) {
    $total = 0;
    foreach($farm->getBarns() AS $barn) {
        $total += count($barn->getAniamls());
    }
    return $total;
}

虽然这行得通,但有没有更好的方法,可以使其更通用吗?如果我想计算动物的腿怎么办?或者一个谷仓有多少扇门,我每次都必须编写一个自定义的 TWIG 扩展.

Although this would work, is there a better way and can it be made more generic? What if I wanted to count Legs on Animals? Or how many Doors a Barn has, I would have to write a custom TWIG extension each time.

推荐答案

使用实体访问器 :

{% for farm in farms %}

  {{ farm.name }}

  {% set barns = farm.getBarns() %}

  Barns count = {{ barns|length }}

  {% for barn in barns %}

    {% set animals = barn.getAnimals() %}

    {{ barn.name }} animals count : {{ animals|length }}

  {% endfor %}

{% endfor %}

这篇关于Symfony2 Twig 获取子实体的总数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆