Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select union in zf2 query

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?

like image 527
Olivier Avatar asked Feb 20 '26 02:02

Olivier


2 Answers

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

like image 96
Abdel Avatar answered Feb 27 '26 08:02

Abdel


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

like image 40
Rob K Avatar answered Feb 27 '26 08:02

Rob K