10.04.2018 Views

Doctrine_manual-1-2-en

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

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

Listing<br />

9-133<br />

// test.php<br />

Listing<br />

9-134<br />

// ...<br />

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

->select('u.username')<br />

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

->leftJoin('u.Email e')<br />

->orderBy('e.address DESC, u.id ASC');<br />

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

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

SELECT<br />

u.id AS u__id,<br />

u.username AS u__username<br />

FROM user u<br />

LEFT JOIN email e ON u.id = e.user_id<br />

ORDER BY e.address DESC,<br />

u.id ASC<br />

Sorting by an aggregate value<br />

In the following example we fetch all users and sort those users by the number of<br />

phon<strong>en</strong>umbers they have.<br />

Listing<br />

9-135<br />

// test.php<br />

Listing<br />

9-136<br />

// ...<br />

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

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

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

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

->orderby('count');<br />

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

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

SELECT<br />

u.id AS u__id,<br />

u.username AS u__username,<br />

COUNT(p.id) AS p__0<br />

FROM user u<br />

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

ORDER BY p__0<br />

Using random order<br />

In the following example we use random in the ORDER BY clause in order to fetch random<br />

post.<br />

Listing<br />

9-137<br />

// test.php<br />

// ...<br />

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

->select('t.id, RANDOM() AS rand')<br />

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

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

Saved successfully!

Ooh no, something went wrong!