++ Introduction Doctrine_RawSql provides convient interface for building raw sql queries. Similar to Doctrine_Query, Doctrine_RawSql provides means for fetching arrays and objects, the way you prefer. Using raw sql for fetching might be useful when you want to utilize database specific features such as query hints or the CONNECT keyword in Oracle. Creating Doctrine_RawSql object is easy: $q = new Doctrine_RawSql(); Optionally a connection parameter can be given: $q = new Doctrine_RawSql($conn); // here $conn is an instance of Doctrine_Connection ++ Component queries The first thing to notice when using Doctrine_RawSql is that you always have to place the fields you are selecting in curly brackets {}. Also for every selected component you have to call addComponent(). The following example should clarify the usage of these: $q = new Doctrine_RawSql(); $q->select('{u.*}') ->from('user') ->addComponent('user', 'User'); // here we tell that user table is bound to class called 'User' $users = $q->execute(); $user[0]; // User object Pay attention to following things: # Fields must be in curly brackets # For every selected table there must be one addComponent call ++ Fetching from multiple components When fetching from multiple components the addComponent calls become a bit more complicated as not only do we have to tell which tables are bound to which components, we also have to tell the parser which components belongs to which. Consider the following model: // file User.php class User extends Doctrine_Record { public function setTableDefinition() { $this->hasColumn('name', 'string', 20); } public function setUp() { $this->hasMany('Phonenumber', array('local' => 'id', 'foreign' => 'user_id')); } } // file Phonenumber.php class Phonenumber extends Doctrine_Record { public function setTableDefinition() { $this->hasColumn('phonenumber', 'string', 20); $this->hasColumn('user_id', 'integer'); } public function setUp() { $this->hasOne('User', array('local' => 'user_id', 'foreign' => 'id', 'onDelete' => 'CASCADE')); } } In the following example we fetch all users and their phonenumbers: $q = new Doctrine_RawSql(); $q->select('{u.*}, {p.*}') ->from('user u LEFT JOIN phonenumber p ON u.id = p.user_id') // here we tell that user table is bound to class called 'User' // we also add an alias for User class called 'u' // this alias will be used when referencing to User class ->addComponent('u', 'User u') // here we add another component that is bound to table phonenumber // notice how we reference that the Phonenumber class is "User's phonenumber" ->addComponent('p', 'u.Phonenumber p'); $users = $q->execute(); $user[0]; // User object