ZF2分页不适用于Union

时间:2015-05-14 07:30:49

标签: php mysql pagination zend-framework2 union

我正在使用PHP Zend Framework 2.3.3。我使用Paginator进行了Union的选择。 代码是这样的:

        $where = new Where();
        $where->like('value', "%$infoToSearch%");
        $select = new Select();
        $select->columns(array(new Expression('DISTINCT(id)')));
        $select->from('products');
        $select->where($where);

        $select2 = new Select();
        $select2->columns(array(new Expression('DISTINCT(id)')));
        $select2->from('products_archive');
        $select2->where($where);

        $select->combine($select2);

        $paginatorAdapter = new DbSelect($select, $this->getAdapter());
        $paginator = new Paginator($paginatorAdapter);

        $paginator->setCurrentPageNumber(1);
        $paginator->setItemCountPerPage(10);

        foreach($paginator as $product){
                var_dump($product);
        }

然后我得到错误的产品数量。我检查了mysql查询日志并看到了这个查询:

( SELECT DISTINCT(id) AS Expression1 FROM `products` WHERE `value` LIKE '%3%' LIMIT 10 OFFSET 0 ) UNION ( SELECT DISTINCT(id) AS Expression1 FROM `products_archive` WHERE `value` LIKE '%3%' )

正如您所看到的,LIMIT 10 OFFSET 0位置错误。它应该在查询结束时。它是一个Bug还是有办法解决这个问题?

1 个答案:

答案 0 :(得分:3)

这是因为select被传递给union的第一部分的分页适配器,所以limit子句应用于该部分。为了允许将limit子句应用于union的结果,需要一个新的SQL \ Select实例,这与之前由Ralph Schindler https://github.com/zendframework/zf2/issues/5162#issuecomment-36294281解决的这个问题非常相似。

为了解决这个问题,你需要传递一个新的选择对象:

$union = (new \Zend\Db\Sql\Select)->from(['sub' => $select]);
$paginatorAdapter = new DbSelect($union, $this->getAdapter());
相关问题