Using Phalcon Model, how can I get distinct rows when get rows using the find()
method.
Phalcon: how to get distinct models?
8.6k views Asked by Real Dreams At
6
There are 6 answers
0
On
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
]
]
);
0
On
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();
}
2
On
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();
Using builder:
Basic implementation for later example:
Distinct command:
Column thing works too, but not recommended:
Using strictly model:
For count:
And less recommended way according to previous answer:
And link to imo best docs.
Also, there are some issues in Phalcon 2.0.2.