1
0
mirror of synced 2024-12-15 15:46:02 +03:00
doctrine2/manual/new/docs/en/dql-doctrine-query-language/order-by-clause.txt
jepso 9b61957154 - New feature in documentation: you can now link to other documentation sections with the following syntax:
- [doc getting-started:installation], or
    - [doc getting-started:installation Custom link text]
- Updated Text_Wiki to 1.2.0
- Documentation should now pass XHTML validator
- Formatted DSN section so that it's easier on eyes
- The single quotes in <code type='php'> won't work anymore due to the Text_Wiki update. Use double quotes instead: <code type="php">. The single quotes have been converted to double quotes in documentation files.
- Modified the links in h1-h6 headings to use the same style as the headings.
- Some refactoring
2007-07-20 08:03:04 +00:00

59 lines
1.4 KiB
Plaintext

+++ 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:
<code>
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.
<code>
FROM User u LEFT JOIN u.Email e
ORDER BY e.address DESC, u.id ASC;
</code>
+++ Sorting by an aggregate value
In the following example we fetch all users and sort those users by the number of phonenumbers they have.
<code type="php">
$q = new Doctrine_Query();
$users = $q->select('u.*, COUNT(p.id) count')
->from('User u')
->innerJoin('u.Phonenumber p')
->orderby('count');
</code>
+++ Using random order
In the following example we use random in the ORDER BY clause in order to fetch random post.
<code type="php">
$q = new Doctrine_Query();
$posts = $q->select('p.*, RANDOM() rand')
->from('Post p')
->orderby('rand')
->limit(1)
->execute();
$randomPost = $posts[0];
</code>