[英]Doctrine How to get result in one row when using addSelect query
[英]How to fetch addSelect query result as single entity?
我有
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 将使用实体填充数组。
这应该会导致您要求的结果。 未测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.