Using Phalcon Model, how can I get distinct rows when get rows using the find()
method.

- 17,114
- 22
- 95
- 173
6 Answers
Using builder:
Basic implementation for later example:
$queryBuilder = $this->getDI()->getModelsManager()
->createBuilder()
->addFrom('tableName', 't');
Distinct command:
$queryBuilder->distinct('t.id');
Column thing works too, but not recommended:
$queryBuilder->columns('DISTINCT(t.id) AS id')
Using strictly model:
// we are waiting for it, but may still not be implemented
TableModel::find(array('distinct' => 'id'))
For count:
TableModel::count(array("distinct" => "id"));
And less recommended way according to previous answer:
TableModel::find(array('columns' => 'distinct(id)'))
And link to imo best docs.
Also, there are some issues in Phalcon 2.0.2.

- 4,761
- 2
- 19
- 41
If you have declared some columns you can use:
$result = Word::find(['columns'=>'distinct foo']);

- 17,114
- 22
- 95
- 173
In phalcon 3.x it looks like to do a distinct with the Models Manager, the distinct method take a boolean as a parameter. So to do a distinct on a column you should do that:
$queryBuilder = $this->getDI()->getModelsManager()
->createBuilder()
->addFrom('tableName', 't')
->columns('t.myColumn')
->distinct(true)
->getQuery()
->execute();
-
This is false: https://github.com/phalcon/cphalcon/blob/master/phalcon/mvc/model/query/builder.zep#L299 – Tim Nov 12 '18 at 13:21
-
This is the answer I was looking for, thanks. I just needed to add some parameter to existing code but adding just ->distinct() or with the name of the field didn't work. I work with the 4th version of Phalcon. For anyone else looking `->distinct(true)` is the right thing to do. – Krzysztof Dabrowski Jun 29 '21 at 14:34
On some occasions you might wish to use it on model initialization, here is example:
/**
* Class MyModel
* @property \Phalcon\Mvc\Model\Resultset\Simple referenceAlias
* @method int countReferenceAlias
*/
class MyModel extends \Phalcon\Mvc\Model
{
public function initialize(): void
{
$this->setSource('my_model');
$this->hasMany('id', 'ReferenceModel', 'reference_id', [
'alias' => 'referenceAlias',
'params' => ['distinct' => 'user_id']
]);
}
}
So later on you can make calls this way:
print $myModel->countReferenceAlias();
or
foreach($myModel->referenceAlias() as $userReference){
print $userReference->user->getName();
}

- 6,028
- 5
- 37
- 61
You can define that in your model::initialize() method:
$this->hasManyToMany(
'asset_id',
'NameSpace\AssetsCategory',
'asset_id',
'category_id',
'NameSpace\Category',
'category_id',
[
'alias' => 'SimilarAssets',
'params' => [
'group' => 'NameSpace\Category.category_id' // remove duplicate data
]
]
);

- 1
- 3
Use the group keyword.
$result = TableModel::find(array("x_id = $x_id","group"=>"uid"));
You can add as many additional arguments to the first section with x_id such as
x_id = $x_id AND y_id = 100
The second portion is where you specify the field you want to group for TableModel.

- 152
- 1
- 2
- 16