ZF2 分页不适用于 Union

ZF2 Pagination does not work with Union

我正在使用 PHPZend Framework 2.3.3。我将 Paginator 用于 Select 和 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还是有什么办法可以解决这个问题?

发生这种情况是因为 select 被传递到联合的第一部分的分页适配器,因此限制子句应用于该部分。为了允许将限制子句应用于联合的结果,需要一个新的 SQL\Select 实例,这与 Ralph Schindler https://github.com/zendframework/zf2/issues/5162#issuecomment-36294281.[=12= 之前解决的这个问题非常相似]

为了解决这个问题,您需要像这样传递一个新的 select 对象:

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