We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

More efficient way to sort \Phalcon\Mvc\Model\Resultset

Hi, since subqueries hasn't been supported in phql, I need to sort my pagination items in PHP. I've done like this code below. It worked, but it uses iterator_to_array which dumps the Resultset to array. Is there more efficient, less memory usage other than this approach?

namespace BI;

class PradSorter {
    public static function cmp($a, $b){
        if($a->row_count == $b->row_count)
            return 0;
        return $a->row_count > $b->row_count ? +1 : -1;
    }

    public static function sort(\Phalcon\Mvc\Model\Resultset $x){
        $x = iterator_to_array($x);
        usort($x, ['\BI\PradSorter', 'cmp']);
        return $x;
    }
} 


98.9k

You can order the resultset in the database rather than doing it in PHP:

$robots = Robots::find(['order' => 'row_count']);
$robots = Robots::find(['order' => 'row_count DESC']);

@Phalcon, of course I know the 'order' option, I've been using it since ver 0.7.0 :) What I'm trying to achieve is this:

SELECT x.* FROM(
SELECT `prad`.* 
FROM `prad` AS `prad`
ORDER BY `prad`.`publish_dt` DESC LIMIT 25
) as x
ORDER BY x.row_count

Since, PHQL not support subquery I fetch prad sorted by publish_dt using query builder pagination, And then I have to sort the Resultset by row_count in PHP