Problem:
I want to change the order in which my records are returned, in SQL this is 'order by my_field ASC'. I see that the pxdb_collection class has the set_order() method, but when I try this it doesn't seem to work. My code is:
$Records = &new pxdb_collection(DATATYPE_DOCUMENT);
$Records->set_order('sunrise DESC');
echo $Records->get_sql();
This prints the following SQL query to the browser:
SELECT DISTINCT
r.approved, r.created, r.datatype, r.id, r.modified, r.`name` AS `title`, r.`sunrise`, r.`sunset`,
...
FROM
records r
WHERE
r.datatype IN (5)
AND r.approved = 1
ORDER BY r.name DESC
Why is this not changing the order from the default 'r.name' to 'r.sunrise DESC'?
The answer is that you have to run pxdb_collection's internal/default filter before it will add the set_order() filter to the base SQL. Thus, you need to call the pxdb_collection::find() method before the set_order() will take affect on the SQL:
$Records = &new pxdb_collection(DATATYPE_DOCUMENT);
$Records->set_order('sunrise DESC');
$Records->find();
echo $Records->get_sql();