GROUP and COUNT() ages in CakePHP

后端 未结 4 1125
悲&欢浪女
悲&欢浪女 2021-01-05 19:34

I\'m trying to group by date of birth and count based on the results, using CakePHP. Here\'s my query.

$data = $this->User->find(\'all\', array(
    \         


        
4条回答
  •  甜味超标
    2021-01-05 19:58

    I think you are getting numeric indexes on your results array because the fields you are adding haven't been generated by CakePHP. CakePHP usually generates queries (and field names) more like this in SQL:

    SELECT `Item`.`id`, `Item`.`name` FROM `items` AS `Item` WHERE 1 = 1 ORDER BY `Item`.`name` ASC
    

    You should try and mimic CakePHP's field naming conventions when adding custom elements to your queries, if you want CakePHP to better understand and format the results coming back from MySQL:

    $age = "DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT(User.dob, '%Y') - (DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT(User.dob, '00-%m-%d'))";
    $data = $this->User->find('all', array(
        'conditions' => array('User.age >' => 20),
        'fields' => array(
            $age . ' AS `User`.`age`',
            'COUNT(id) AS `User`.`count`'
        ),
        'group' => 'User.age'
    ));
    

    Maybe this will give you more luck getting the conditions to work. :)

提交回复
热议问题