4

I'm programming a TYPO3 - extension for a website. Since I'm using the Extbase Framework I have a Repository class (Tx_Extbase_Persistence_Repository) where I do two sql queries in a row:

$query1 = $this->createQuery();
$query1->statement($sql1);
$res1 = $query1->execute();

$query2 = $this->createQuery();
$query2->statement($sql2);
$res1 = $query2->execute();

Both $res1 and $res2 contain a Tx_Extbase_Persistence_QueryResult. Now I want to return the combined result and I have no idea how this is done. Returning the raw array isn't an option because I'm relying on the functions of the QueryResult class, and also I want to avoid to combine the sql(UNION, JOIN). I already tried this:

$myResult = $this->objectManager->create('Tx_Extbase_Persistence_ObjectStorage')
foreach($res1 as $obj) {
    $myResult->attach($obj);
}
//foreach $res2

..but this throws an error ("could not determine the child object type")

So how do you properly combine two Tx_Extbase_Persistence_QueryResult ?

Edit:

With combining I mean instead of two separate QueryResults I want just one which contains both the results from $query1 as well as $query2. An SQL-UNION or JOIN unfortunately isn't an option.

Fabian Fritz
  • 370
  • 3
  • 14

3 Answers3

7

QueryResult implements QueryResultInterface which extends among others ArrayAccess. With this you can use the offsetSet method.

foreach ($res2->toArray() as $result) {
  $res1->offsetSet(($res1->count()), $result);
}

The QueryResult $res1 contain now the objects from $res2 too.

fazzyx
  • 1,564
  • 1
  • 12
  • 14
  • This works, but has a crucial flaw. It indicates the wrong count. It shows the count of the first QueryResult. So if you insert One with 10 items and one with 20 items, the merged Result will contain all 30 items, but `$res1->count()` will show only 10! – Naderio Nov 23 '18 at 08:09
2

If you dont need the QueryResult-Object you can do this by using array_merge.

$res1 = $this->createQuery()->execute();
$res2 = $this->createQuery()->execute();
$res = array_merge($res1->toArray(), $res2->toArray());
crz
  • 31
  • 5
0

It's hard to guess what are you mean by writing combined result, however, I'm just guessing, that you should use custom $query->statement($sql) where you should get single result using SQL's joins etc.

biesior
  • 54,554
  • 10
  • 118
  • 177