I am moving my web application from zf1 to zf2 and among the problems I have with sql queries, I can't figure out how to make a union.
I used to be able to make
$select->union($select1, $select2, $select3)
but the Zend\Db\Sql\Select does not have an union() method anymore.
Is there still a way to make an union in a query with zf2?
I use this https://github.com/zendframework/zf2/pull/3962. (union of two select queries).
Just to complete this answer, I use this to combine/union of 3 selects :
$Sql = new Sql ( $adapter );
$select1 = $Sql->select();
$select1->from(...);
$select2 = $Sql->select();
$select2->from(...);
//union of two first selects
$select1->combine ( $select2 );
//create the third select
$select3 = $Sql->select();
$select3->from(...);
//Final select
$select = $Sql->select();
$select->from(array('sel1and2' => $select1));
$select->combine ( $select3 );
$select->order($order);
Be careful order by not work with combine ! see ZF2 Union + Pagination
As an alternative for those wanting ease with >1 UNIONs, ZF2 has a dedicated class Zend\Db\Sql\Combine:
new Combine(
[
$select1,
$select2,
$select3,
...
]
)
or
(new Combine)->union($select);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With