我知道
Foo实体:
class Foo
{
private $name;
/**
* @ORM\OneToMany(targetEntity="App\Entity\Bar", mappedBy="foo", orphanRemoval=true)
*/
private bars;
...
}
酒吧实体
class Bar
{
private $baz
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Foo", inversedBy="bars")
* @ORM\JoinColumn(nullable=false)
*/
private $foo;
...
}
Foo存储库:
$qb = $this->createQueryBuilder('f')
->select('f as foo')
->leftJoin('f.bars', 'b')
->addSelect('b')
->addSelect('SUM(b.baz) as baz_total')
->having('SUM(b.baz) > 0')
->groupBy('f.id')
->orderBy('f.id', 'ASC')->getQuery()->getResult();
单行结果如下:
array(
'foo' => array( // Foo Entity
...
'name' => ...,
'bars' => array(...)), //ArrayCollection
'baz_total' //scalar value
)
和神庙看起来像:
{% for row in foos %}
{{ row.foo.name }}
{{ row.baz_total}}
{% endfor %}
有什么办法可以使它像:
结果:
array(
'name' => ...,
'bars' => array(...)), //ArrayCollection
'baz_total' // extra select as part of entity
) ...
模板:
{% for foo in foos %}
{{ foo.name }}
{{ foo.baz_total}}
{% endfor %}
将您的foo存储库更改为:
$qb = $this->createQueryBuilder('f')
->select('f, b, SUM(b.baz) as baz_total')
->leftJoin('f.bars', 'b')
->having('SUM(b.baz) > 0')
->groupBy('f.id')
->orderBy('f.id', 'ASC')->getQuery()->getResult();
如果需要完整的实体,只需“选择”别名。 Symfony将使用实体填充数组。
这应该会导致您请求的结果。未测试。