How to use distinct in Zend Framework 2?
Asked Answered
K

4

23

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

Kaneshakang answered 11/3, 2013 at 20:34 Comment(1)
I
20

Use an expression in your column selection.

$select = new Select('tablename');
$select->columns(array(new Expression('DISTINCT(id) as id')));
Imitate answered 12/3, 2013 at 16:16 Comment(2)
also $select->columns(array('id' => new Expression('DISTINCT(id)'))); Key will become aliasOmbre
This is a hack, and wrong. "distinct" is a property of the row, not of the column. Once you want more than one column, this will not work at all.Apochromatic
P
35

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');
Pelion answered 24/6, 2013 at 15:5 Comment(1)
This is the proper answer and should be marked as answerKape
I
20

Use an expression in your column selection.

$select = new Select('tablename');
$select->columns(array(new Expression('DISTINCT(id) as id')));
Imitate answered 12/3, 2013 at 16:16 Comment(2)
also $select->columns(array('id' => new Expression('DISTINCT(id)'))); Key will become aliasOmbre
This is a hack, and wrong. "distinct" is a property of the row, not of the column. Once you want more than one column, this will not work at all.Apochromatic
L
20

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)
Lapith answered 29/9, 2013 at 20:33 Comment(0)
H
0

This worked best for me.

$select = $this->select()
          ->distinct()
          ->where('user_id = ?', $user_id);

http://webphplearn.com/blog/blogdetail/Distinct_in_Zendframework2

Holmgren answered 15/10, 2018 at 11:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.