2007-06-14 18:36:18 +04:00
+++ Introduction
Record collections can be sorted efficiently at the database level using the ORDER BY clause.
Syntax:
<code>
[ORDER BY {ComponentAlias.columnName}
[ASC | DESC], ...]
</code>
Examples:
2007-09-06 20:31:07 +04:00
<code type="sql">
2007-06-14 18:36:18 +04:00
FROM User u LEFT JOIN u.Phonenumber p
ORDER BY u.name, p.phonenumber
FROM User u, u.Email e
ORDER BY e.address, u.id
</code>
In order to sort in reverse order you can add the DESC (descending) keyword to the name of the column in the ORDER BY clause that you are sorting by. The default is ascending order; this can be specified explicitly using the ASC keyword.
2007-09-06 20:31:07 +04:00
<code type="sql">
2007-06-14 18:36:18 +04:00
FROM User u LEFT JOIN u.Email e
ORDER BY e.address DESC, u.id ASC;
</code>
2007-06-14 01:30:32 +04:00
+++ Sorting by an aggregate value
2007-06-14 18:50:14 +04:00
2007-06-19 23:20:33 +04:00
In the following example we fetch all users and sort those users by the number of phonenumbers they have.
2007-07-20 12:03:04 +04:00
<code type="php">
2007-06-14 18:50:14 +04:00
$q = new Doctrine_Query();
$users = $q->select('u.*, COUNT(p.id) count')
->from('User u')
->innerJoin('u.Phonenumber p')
->orderby('count');
</code>
2007-06-14 01:30:32 +04:00
+++ Using random order
2007-06-14 18:50:14 +04:00
2007-06-19 23:20:33 +04:00
In the following example we use random in the ORDER BY clause in order to fetch random post.
2007-07-20 12:03:04 +04:00
<code type="php">
2007-06-14 18:50:14 +04:00
$q = new Doctrine_Query();
$posts = $q->select('p.*, RANDOM() rand')
->from('Post p')
->orderby('rand')
->limit(1)
->execute();
$randomPost = $posts[0];
</code>