如何在分页学说2本机查询?(How to paginate a native query in Do

2019-08-07 19:46发布

教义2具有教义\ ORM \工具\其可用于进行分页正常DQL查询分页\分页程序类。

但是,如果我通过它本机查询,我得到这个错误:

Catchable fatal error: Argument 1 passed to Doctrine\ORM\Tools\Pagination\Paginator::cloneQuery() must be an instance of Doctrine\ORM\Query, instance of Doctrine\ORM\NativeQuery given

我试着删除类型,提示从cloneQuery方法分页程序类,但这恰恰提供了进一步的错误,因为分页程序类的其他位预计查询发现,不是NativeQuery方法。

是否有分页本地查询,而不需要建立一个新的分页程序类或从数据库中每行读取到一个数组的任何简单的方法?

Answer 1:

我做了我自己的分页程序适配器类Zend_Paginator的兼容。

可能不会是最灵活的,因为它依赖于有是一个“FROM”查询(见计数()方法)附近开始,但它是一个相对快速和容易修复。

/**
 * Paginate native doctrine 2 queries 
 */
class NativePaginator implements Zend_Paginator_Adapter_Interface
{
    /**
     * @var Doctrine\ORM\NativeQuery
     */
    protected $query;
    protected $count;

    /**
     * @param Doctrine\ORM\NativeQuery $query 
     */
    public function __construct($query)
    {
        $this->query = $query;
    }

    /**
     * Returns the total number of rows in the result set.
     *
     * @return integer
     */
    public function count()
    {
        if(!$this->count)
        {
            //change to a count query by changing the bit before the FROM
            $sql = explode(' FROM ', $this->query->getSql());
            $sql[0] = 'SELECT COUNT(*)';
            $sql = implode(' FROM ', $sql);

            $db = $this->query->getEntityManager()->getConnection();
            $this->count = (int) $db->fetchColumn($sql, $this->query->getParameters());
        }

        return $this->count;
    }

    /**
     * Returns an collection of items for a page.
     *
     * @param  integer $offset Page offset
     * @param  integer $itemCountPerPage Number of items per page
     * @return array
     */
    public function getItems($offset, $itemCountPerPage)
    {
        $cloneQuery = clone $this->query;
        $cloneQuery->setParameters($this->query->getParameters(), $this->query->getParameterTypes());

        foreach($this->query->getHints() as $name => $value)
        {
            $cloneQuery->setHint($name, $value);
        }

        //add on limit and offset
        $sql = $cloneQuery->getSQL();
        $sql .= " LIMIT $itemCountPerPage OFFSET $offset";
        $cloneQuery->setSQL($sql);

        return $cloneQuery->getResult();
    }
}


Answer 2:

如果你有一个DBAL查询构建器(您已经以$ yourDbalQueryBuilder = $连接 - > createQueryBuilder()构造;),那么你可以使用:

$ yourDbalQueryBuilder-> setFirstResult(0) - > setMaxResults(100000000) - >执行() - > rowCount时();



文章来源: How to paginate a native query in Doctrine 2?