We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Option for function distinct phalcon/mvc/collection

Hello! I need to make a find, normally I would use distinct, but I not found an option in phalcon.

My class as below :

class Calls extends \Phalcon\Mvc\Collection { public $agent; public $number; public $date; public $status; }

I need to use distinct fields date and number .

Thanks, Murillo

edited Jul '16

Just an update on how to get distinct results based on search query. i did a lot of research on this and decided to share.

I hope this code will help others to achive needed results.

  1. You will need to use Database adapter for the new MongoDB extension library from incubator 2.1 and add custom code inside your collection.

in my case i did it like this. In my Products collection i created static method findDistinctBySearch


<?php
use Phalcon\Mvc\MongoCollection;

class Products extends MongoCollection
{
public $storeId;
public $title;
public static function findDistinctBySearch($fieldName,$filter=[],$options = [])
    {

        $className = get_called_class();

        /** @var MongoCollection $collection */
        $collection = new $className();

        $connection = $collection->getConnection();

        return $connection->selectCollection($collection->getSource())->distinct($fieldName, $filter, $options);

    }
}

Search by title, distinct by 'storeId' and limit by 2

        $options = [
             'limit' => 2
         ];
         $search = [
             'title' => 'Galaxy 14 Tanning Bed'
         ];

         $distinct = Products::findDistinctBySearch('storeId', $search, $options);

Another example with full text search

        $search['$text'] = ['$search' => 'Search Query'];
        $options["projection"] = ['score' => ['$meta' => "textScore"]];
        $options["sort"] = ["score" => ['$meta' => "textScore"]];
        $options["limit"] = 2;

        $distinct = Products::findDistinctBySearch('storeId',$search,$options);