Sorting not working as expected for collection

Running into an odd issue where a collection of mine isn’t sorting by two fields which both of them share. Below is the code in question thus far.

<?php
return function($site, $pages, $page) {
    // send the XML header
    header::type('text/xml');
    
    // Features
    $features = $pages->find('features/2016')->children()->visible()->sortBy('date', 'desc', 'time', 'desc')->limit(10);
    
    // [News]
    $news = new Pages();
    $newsFiltered = $pages->find('news/'.date('Y').'/'.date('m'))->children()->visible()->sortBy('date', 'desc', 'time', 'desc')->limit(10);

    if (sizeof($newsFiltered) > 0) {
        $news->add($newsFiltered);
    }

    if (count($newsFiltered) < 11) {
        $newsFiltered_Previous = $pages->find('news/'.date('Y', strtotime('-1 month')).'/'.date('m', strtotime('-1 month')))->children()->visible()->sortBy('date', 'desc', 'time', 'desc')->limit(11 - count($newsFiltered));
        
        $news->add($newsFiltered_Previous);
    }
    
    // generate the combined RSS feed
    $feed = new Pages();
    
    $feed->add($features);
    $feed->add($news);
    
    // order the combined RSS feed
    $feed->sortBy('date', 'desc', 'time', 'desc')->limit(10);
    
    // pass the variables back to the template
    return compact('feed');
};

Looking at the result, both the sortBy() and limit() on $feed aren’t taking effect. There’s some slightly differences in the blueprints, but the date and time fields both exist in each of them. So in theory there shouldn’t be any issue then you’d think.

Any ideas what the issue could be?

sortBy and limit don’t change the collection, they return a sorted / limited copy of the collection.

So, just assign the result to your $feed variable like this:

$feed = $feed->sortBy('date', 'desc', 'time', 'desc')->limit(10);
1 Like

Ah, that makes sense now with how it was behaving before — it’s working as expected after that fix.

Thanks! :slight_smile: