CakePHP 1.3.x find('count') with 'contains', 'group', 'order' and 'limit' statement for SQL equivalent

1.7k views Asked by At

I am currently performing a Model->query() instead of Model->find() as I can't seem to do a 'count' with 'contains', 'group', 'order' and 'limit' to represent this SQL statement.

    $data = $this->Instruction->query("
            SELECT `Source`.`company_name`, COUNT(*) AS `count`
            FROM `instructions` AS `Instruction`
            LEFT JOIN `sources` AS `Source` ON (`Instruction`.`source_id` = `Source`.`id`)
            GROUP BY source_id
            ORDER BY count DESC
            LIMIT 5"
    );

Preference would be to perform a Model->find('count') or even a Model->find('all') with the appropriate 'contains', 'group', 'order' and 'limit' but I am having no such luck.

1

There are 1 answers

1
malar On BEST ANSWER

Try this: $options = array(

                'fields'=>array('Source.company_name','COUNT(*) as `count`'),
                'joins' => array('LEFT JOIN `sources` AS Source ON `Source`.`id` = `Instruction`.`id`'),
                'group' => '`source_id`',
                'order' => array('count' => 'DESC'),'limit' => 5
            );

            return $this->Instruction->find('all', $options);