AKKAweb
AKKAweb

Reputation: 3807

CakePHP 1.3: How to represent the following MySQL code with Count(*) AS Total

I need help converting the following MySQL code to a CakePHP find function

$users= mysql_query(
    "SELECT country, COUNT(*) AS total FROM users
        GROUP BY country
        ORDER BY total DESC
        LIMIT 15"
);

This is the CakePHP find code I have so far. However, I am missing the COUNT(*) AS Total

$users= $this->User->find(
    'all',
    array(
        'fields' => array(
            'country'
        ),
        'group' => 'country',
        'order' => 'country DESC',
        'limit' => 10
    )
);

Thank you,

Upvotes: 0

Views: 598

Answers (2)

thecodeparadox
thecodeparadox

Reputation: 87083

$this->User->find('all', array(
   'fields' => array('User.country', 'COUNT(*) AS total'),
   'group' => 'country',
   'order' => array('User.country' => 'DESC'),
   'limit' => 15
));

Upvotes: 2

Tom
Tom

Reputation: 3847

use find->count to count your users: http://book.cakephp.org/1.3/view/1020/find-count

and regular find all to get your users info.

$conditions = array("User.active" => 1);
$num_users = $this->User->find('count',array("conditions" => $conditions));
$users = $this->User->find('all',array("conditions" => $conditions));
$this->set(compact('users','num_users'));

Upvotes: 2

Related Questions