spotorm / spot2

Spot v2.x DataMapper built on top of Doctrine's Database Abstraction Layer
http://phpdatamapper.com
BSD 3-Clause "New" or "Revised" License
601 stars 101 forks source link

Calculating total rows of a (limited) \Spot\Query #260

Open Pnoexz opened 6 years ago

Pnoexz commented 6 years ago

When getting paginated results, it's often common to also need the total rows for the query. I always hated doing this because I had to do the same query twice but only changing the select and limit parts of the query. Today, after reading the source code for both \Spot\Query and \Doctrine\DBAL\Query\QueryBuilder I found a much simpler way to do this. Following the lines of \Spot\Query::count(), I came up with:

   /**
     * Takes a Query object as a parater and removes the limit part of the
     * query, replaces the select with a simple COUNT(*), and removes the
     * order to slightly improve performance.
     *
     * @param Query $query
     *
     * @return int
     */
    protected function getTotalItemsFromQuery(Query $query): int
    {
        $countQuery = clone $query;
        $countQuery
            ->select('COUNT(*)')
            ->order([])
            ->limit(null, null);
        return $countQuery->count();
    }

Is it worth to look into adding this as a built-in feature or would it just be better to edit the documentation? Or is there an already way to do this that I've missed?