Best way of getting count(*) when using group by.

Hello!

I'm curious about the best way of adding a "count(id)" to a magic get on a model? Example:

<?php

class Notification extends \Phalcon\Mvc\Model {

   public function initialize() {
        $this->hasMany('id', 'Notification', 'user_id');
   }

   public function getNotifications() {
        $notifications = $this->getNotification(
            array(
                "group" => "reason"
            );
        );

        // How do I find out the count(id) of each resulted row? $notification[0]->count() returns the total count of $notification.
    }

}

Thanks.

Best regards, dimhoLt

Edit: I'm currently using the solution of creating a custom query builder, but I'm still interested in some best-practices advice.



83.2k

Try this:

<?php

class Notification extends \Phalcon\Mvc\Model {

   public function initialize() {
        $this->hasMany('id', 'Notification', 'user_id');
   }

   public function getNotifications() {
        return $this->getNotification(
            array(
                "columns" => "count(id)",
                "group" => "reason"
            );
        );
    }

}