Search code examples
phpyiicountcriteria

how can get count field in crirteria?


I'm trying to build a query that has a group by user_id, select user_id,count(id) , condition, join. i can get a true result by findall command but only i can not show count(id) i left my code here

in controller

       $criteria=new CDbcriteria();
        $criteria->condition = 'serviceId=:serviceId';
        $criteria->params = array(':serviceId'=>1);
        $criteria->group = 't.user_Id';
        $criteria->select = array('t.user_Id,count(psh_profile_information_services.id) AS count');
        $criteria->join = 'left join psh_profile_information_services on t.id=psh_profile_information_services.profileInformationId';
        $moli=  ProfileInformation::model()->findAll($criteria);
        $this->render('conectionpoint', array('moli'=>$moli ));

in view

foreach ($moli as $mol)
        {
            echo "user_Id:  ".$mol->user_id." --- count:".???????? ;

        }

print $mol

ProfileInformation Object ( [_new:CActiveRecord:private] => [_attributes:CActiveRecord:private] => Array ( [user_Id] => 1 [createDate] => 1393/03/23 - 15:49:26 [modifiedDate] => 1393/03/23 - 15:49:26 ) [_related:CActiveRecord:private] => Array ( ) [_c:CActiveRecord:private] => [_pk:CActiveRecord:private] => [_alias:CActiveRecord:private] => t [_errors:CModel:private] => Array ( ) [_validators:CModel:private] => [_scenario:CModel:private] => update [_e:CComponent:private] => [_m:CComponent:private] => )

Solution

  • In ProfileInformation class file -

    class ProfileInformation extends ActiveRecord
    {
        $public $total_info;
        [....] //Rest of the code.
    

    In Controller Action, change -

    $criteria->select = array('t.user_Id,count(psh_profile_information_services.id) AS count');

    to

    $criteria->select = array('t.user_Id,count(psh_profile_information_services.id) AS total_info');

    In view file -

    foreach ($moli as $mol)
    {
        echo "user_Id:  ".$mol->user_id." --- count:".$mol->total_info;
    }
    

    This should work fine.

    If not, then just do simple debug -

    echo "<pre>";
    
    foreach($moli as $mol) {
        echo 'Total Info: ' . $mol->total_info . "<br />";
        foreach($mol as $key => $value) {
            echo $key . ' ' . $value . "<br />";
        }
        echo "<br />";
    }
    
    exit();
    

    and check the values.