简体   繁体   中英

How to fetch addSelect query result as single entity?

I got

Foo entity:

class Foo
{
  private $name;

  /**
    * @ORM\OneToMany(targetEntity="App\Entity\Bar", mappedBy="foo", orphanRemoval=true)
    */
  private bars;
  ...
}

Bar entity

class Bar
{
  private $baz

   /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Foo", inversedBy="bars")
     * @ORM\JoinColumn(nullable=false)
     */
  private $foo;
  ...
}

Foo repositiory:

$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();

a single row the result looks like:

array(
  'foo' => array( // Foo Entity
      ...
      'name' => ...,
      'bars' => array(...)), //ArrayCollection 
  'baz_total' //scalar value 
)

and temple looks like:

{% for row in foos %}
  {{ row.foo.name }}
  {{ row.baz_total}}
{% endfor %}

Is there any way make it works like:

result:

array(
  'name' => ...,
  'bars' => array(...)), //ArrayCollection 
  'baz_total' // extra select as part of entity 
) ...

template:

{% for foo in foos %}
  {{ foo.name }}
  {{ foo.baz_total}}
{% endfor %}

Change your foo repository to:

$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();

If you want the full entity, just "select" the alias. Symfony will populate the array with the entity.

That should result in your requested result. Not tested.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM