dql-doctrine-query-language.txt 2.49 KB
Newer Older
phuson's avatar
phuson committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
++ Introduction
++ SELECT queries
++ UPDATE queries
++ DELETE queries
++ FROM clause
++ JOIN syntax
++ INDEXBY keyword
++ WHERE clause
++ Conditional expressions
++ Functional Expressions
++ Subqueries
++ GROUP BY, HAVING clauses
++ ORDER BY clause
++ LIMIT and OFFSET clauses
++ Examples
++ The Query Registry
17

phuson's avatar
phuson committed
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
Doctrine_Query_Registry is a class for registering and naming queries. It helps with the organization of your applications queries and along with that it offers some very nice convenience stuff.

The queries are added using the add() method of the registry object. It takes two parameters, the query name and the actual DQL query.

<code type="php">
$r = Doctrine_Manager::getInstance()->getQueryRegistry();

$r->add('all-users', 'FROM User u');
</code>

+++ Namespaces

The Query registry supports namespaces. The namespace is separated from the actual name with / -mark. If the name of the namespace is a record name the given record has all the named queries available in its local scope.

<code type="php">
$r = Doctrine_Manager::getInstance()->getQueryRegistry();

$r->add('User/all', 'FROM User u');
$r->add('User/byName', 'FROM User u WHERE u.name = ?');

$user = new User();

// find the user named Jack Daniels
$user = $user->findOne('byName', array('Jack Daniels'));

// find all users
$users = $user->find('all');
</code>

++ BNF
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71

++ Magic Finders

Doctrine offers some magic finders for your Doctrine models that allow you to find a record by any column that is present in the model. This is helpful for simply finding a user by their username, or finding a group by the name of it. Normally this would require writing a Doctrine_Query instance and storing this somewhere so it can be reused. That is no longer needed for simple situations like that.

The basic pattern for the finder methods are as follows: findBy%s($value) or findOneBy%s($value). The %s can be a column name or a relation alias. If you give a column name you must give the value you are looking for. If you specify a relationship alias, you can either pass an instance of the relation class to find, or give the actual primary key value.

Examples:
<code type="php">
// The normal find by primary key method
$userTable = Doctrine::getTable('User');

$user = $userTable->find(1);

// Find one user by the username
$userTable = Doctrine::getTable('User');

$user = $userTable->findOneByUsername('jonwage');

// Find phonenumbers for the user above
$phoneTable = Doctrine::getTable('Phonenumber');

$phonenumbers = $phoneTable->findByUser($user);
</code>