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) 148<br />

Listing<br />

9-125<br />

// ...<br />

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

->select('SUM(a.amount)')<br />

->from('Account a');<br />

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

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

SELECT<br />

SUM(a.amount) AS a__0<br />

FROM account a<br />

Using an aggregate function in a statem<strong>en</strong>t containing no GROUP BY clause, results in<br />

grouping on all rows. In the example below we fetch all users and the number of<br />

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

Listing<br />

9-126<br />

// test.php<br />

Listing<br />

9-127<br />

// ...<br />

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

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

->addSelect('COUNT(p.id) as num_phon<strong>en</strong>umbers')<br />

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

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

->groupBy('u.id');<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 />

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

GROUP BY u.id<br />

The HAVING clause can be used for narrowing the results using aggregate values. In the<br />

following example we fetch all users which have at least 2 phon<strong>en</strong>umbers<br />

Listing<br />

9-128<br />

// test.php<br />

// ...<br />

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

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

->addSelect('COUNT(p.id) as num_phon<strong>en</strong>umbers')<br />

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

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

->groupBy('u.id')<br />

->having('num_phon<strong>en</strong>umbers >= 2');<br />

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

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

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

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

Saved successfully!

Ooh no, something went wrong!