Search code examples
phpphalcon

Phalcon: how to get distinct models?


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


Solution

  • 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.