When paginating my user model in CakePHP, I can sort by some values, but not others. I can order the results by created or email fine, for example, but ordering by username or reputation comes back with a list of users in a seemingly arbitrary order. So for instance:
$this->paginate = array('conditions' => array('User.is_active' => true), 'limit' => 24, 'order' => array('User.created' => 'DESC'));
works as expected, but
$this->paginate = array('conditions' => array('User.is_active' => true), 'limit' => 24, 'order' => array('User.reputation' => 'DESC'));
doesn’t.
I thought at first this might be a database issue, but when I search the database directly everything is returned and sorted as expected.
Note: I’m using MongoDB with ichikaway’s MongoDB plugin for CakePHP; paginating users used to work fine, so I’m positive it’s not a bug with the plugin, but something has changed somewhere and I can’t pinpoint what.
Finally, when I view the queries in the debug info, I can see that CakePHP isn’t even passing the order value to the database when searching. The first search above displays this:
db.users.find( {"is_active":true}, [] ).sort( {"created":-1} ).limit( 24 ).skip( 0 )
and the second this:
db.users.find( {"is_active":true}, [] ).sort( [] ).limit( 24 ).skip( 0 )
Why is CakePHP letting me order by some things, but not others?
Oops. It was a database error; somehow, a record got created with only a few of the fields in it (e.g., _id, created, modified, and a few others), which not coincidentally were the only ones that I could sort by. Deleting it got everything back to normal.
Strange that doing a search would work fine, but paginating with the same parameters wouldn’t. Maybe it is a plugin/Cake bug after all?