Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use distinct in Zend Framework 2?

How can I use the distinct clause with Zend\Db\Sql\?

like image 892
Emmanuel Gauthier Avatar asked Mar 11 '13 20:03

Emmanuel Gauthier


3 Answers

I found this very usefull solution on http://blog.abmeier.de/php/zf2-select-distinct

$sql = new Sql($adapter);
$select = $sql->select();
$select->quantifier('DISTINCT');
like image 178
Mihai Avatar answered Nov 12 '22 02:11

Mihai


Use an expression in your column selection.

$select = new Select('tablename');
$select->columns(array(new Expression('DISTINCT(id) as id')));
like image 19
Andrew Avatar answered Nov 12 '22 01:11

Andrew


While Mihai Dobre's answer is correct, I think you should use the constants provided by the framework instead of using a string literal. This will make your code more future-proof.

$sql->select()->quantifier(\Zend\Db\Sql\Select::QUANTIFIER_DISTINCT)
like image 19
Julian Avatar answered Nov 12 '22 01:11

Julian