+++ Introduction

In Doctrine you may express your queries in the native SQL dialect of your database. This is useful if you want to use the full power of your database vendor's features (like query hints or the CONNECT keyword in Oracle).

It should be noted that not all the sql is portable. So when you make database portable applications you might want to use the DQL API instead.


+++ Using SQL

The {{rawSql}} component works in much same way as {{Zend_Db_Select}}. You may use method overloading like {{$q->from()->where()}} or just use {{$q->parseQuery()}}. There are some differences though:

# In {{Doctrine_RawSql}} component you need to specify all the mapped table columns in curly brackets {} this is used for smart column aliasing.
# When joining multiple tables you need to specify the component paths with {{addComponent()}} method

The following example represents a very simple case where no {{addComponent()}} calls are needed. 
Here we select all entities from table entity with all the columns loaded in the records.

<code type="php">
$query = new Doctrine_RawSql($conn);

$query->parseQuery("SELECT {entity.name} FROM entity");
        
$entities = $query->execute();
</code>


+++ Adding components

The following example represents a bit harder case where we select all entities and their associated phonenumbers using a left join. Again we wrap all the columns in curly brackets but we also specify what tables associate to which components.

First we specify that table entity maps to record class {{Entity}}.

Then we specify that table phonenumber maps to {{Entity.Phonenumber}} (meaning phonenumber associated with an entity).

<code type="php">
$query = new Doctrine_RawSql($conn);

$query->parseQuery("SELECT {entity.*}, {phonenumber.*} 
                   FROM entity 
                   LEFT JOIN phonenumber 
                   ON phonenumber.entity_id = entity.id");

$query->addComponent("entity", "Entity");
$query->addComponent("phonenumber", "Entity.Phonenumber");

$entities = $query->execute();
</code>


+++ Method overloading

<code type="php">
$query = new Doctrine_RawSql($conn);

$query->select('{entity.name}')
      ->from('entity');

$query->addComponent("entity", "User");

$coll = $query->execute();
</code>
