10.04.2018 Views

Doctrine_manual-1-2-en

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 9: DQL (<strong>Doctrine</strong> Query Language) 130<br />

JOIN ] [ON | WITH] [INDEXBY]<br />

,<br />

[[LEFT | INNER] JOIN ] [ON | WITH] <br />

[INDEXBY] ,<br />

...<br />

[[LEFT | INNER] JOIN ] [ON | WITH] <br />

[INDEXBY] <br />

DQL supports two kinds of joins INNER JOINs and LEFT JOINs. For each joined compon<strong>en</strong>t,<br />

you can optionally specify an alias.<br />

The default join type is LEFT JOIN. This join can be indicated by the use of either LEFT<br />

JOIN clause or simply ',', h<strong>en</strong>ce the following queries are equal:<br />

Listing<br />

9-43<br />

// test.php<br />

// ...<br />

$q = <strong>Doctrine</strong>_Query::create()<br />

->select('u.id, p.id')<br />

->from('User u')<br />

->leftJoin('u.Phon<strong>en</strong>umbers p');<br />

$q = <strong>Doctrine</strong>_Query::create()<br />

->select('u.id, p.id')<br />

->from('User u, u.Phon<strong>en</strong>umbers p');<br />

echo $q->getSqlQuery();<br />

The recomm<strong>en</strong>ded form is the first because it is more verbose and easier to read and<br />

understand what is being done.<br />

The above call to getSql() would output the following SQL query:<br />

Listing<br />

9-44<br />

SELECT<br />

u.id AS u__id,<br />

p.id AS p__id<br />

FROM user u<br />

LEFT JOIN phon<strong>en</strong>umber p ON u.id = p.user_id<br />

Notice how the JOIN condition is automatically added for you. This is because <strong>Doctrine</strong><br />

knows how User and Phon<strong>en</strong>umber are related so it is able to add it for you.<br />

INNER JOIN produces an intersection betwe<strong>en</strong> two specified compon<strong>en</strong>ts (that is, each and<br />

every record in the first compon<strong>en</strong>t is joined to each and every record in the second<br />

compon<strong>en</strong>t). So basically INNER JOIN can be used wh<strong>en</strong> you want to effici<strong>en</strong>tly fetch for<br />

example all users which have one or more phon<strong>en</strong>umbers.<br />

By default DQL auto-adds the primary key join condition:<br />

Listing<br />

9-45<br />

// test.php<br />

// ...<br />

$q = <strong>Doctrine</strong>_Query::create()<br />

->select('u.id, p.id')<br />

->from('User u')<br />

->leftJoin('u.Phon<strong>en</strong>umbers p');<br />

----------------- Brought to you by

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!