How can I use the distinct
clause with Zend\Db\Sql\
?
How to use distinct in Zend Framework 2?
Asked Answered
github.com/zendframework/zf2/blob/master/library/Zend/Db/Sql/… –
Said
Use an expression in your column selection.
$select = new Select('tablename');
$select->columns(array(new Expression('DISTINCT(id) as id')));
also $select->columns(array('id' => new Expression('DISTINCT(id)'))); Key will become alias –
Ombre
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
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');
This is the proper answer and should be marked as answer –
Kape
Use an expression in your column selection.
$select = new Select('tablename');
$select->columns(array(new Expression('DISTINCT(id) as id')));
also $select->columns(array('id' => new Expression('DISTINCT(id)'))); Key will become alias –
Ombre
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
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)
This worked best for me.
$select = $this->select()
->distinct()
->where('user_id = ?', $user_id);
http://webphplearn.com/blog/blogdetail/Distinct_in_Zendframework2
© 2022 - 2024 — McMap. All rights reserved.