how to convert count(*) and group by queries to yi

2019-07-20 19:47发布

I want to convert this query in yii

SELECT count(*) AS cnt, date(dt) FROM tbl_log where status=2 GROUP BY date(dt) 

and fetch data from that. I try this command (dt is datetime field):

$criteria = new CDbCriteria();
$criteria->select = 'count(*) as cnt, date(dt)';
$criteria->group = 'date(dt)';
$criteria->condition = 'status= 2';
$visit_per_day = $this->findAll($criteria);

but no data will fetch! wath can I do to get data?

标签: select yii count
3条回答
时光不老,我们不散
2楼-- · 2019-07-20 20:15

Try this below code

     $logs = Yii::app()->db->createCommand()
            ->select('COUNT(*) as cnt')
            ->from('tbl_log')  //Your Table name
            ->group('date') 
            ->where('status=2') // Write your where condition here
            ->queryAll(); //Will get the all selected rows from table

Number of visitor are:

    echo count($logs); 

Apart from using cDbCriteria, to do the same check this link http://www.yiiframework.com/forum/index.php/topic/10662-count-on-a-findall-query/

查看更多
疯言疯语
3楼-- · 2019-07-20 20:24

If you use Yii2 and have a model based on table tbl_log, you can do it in model style like that:

$status = 2;
$result = Model::find()
    ->select('count(*) as cnt, date(dt)')
    ->groupBy('date(dt)')
    ->where('status = :status')
    ->params([':status' => $status ])
    ->all();
查看更多
淡お忘
4楼-- · 2019-07-20 20:36

Probably you see no data because you need assign data to model attributes which doesn't exist.

$criteria = new CDbCriteria();
$criteria->select = 'count(*) AS cnt, date(dt) AS dateVar';
$criteria->group = 'date(dt)';
$criteria->condition = 'status= 2';
$visit_per_day = $this->findAll($criteria);

This means that your model must have attributes cnt and dateVar in order to show your data. If you need custom query then check Hearaman's answer.

查看更多
登录 后发表回答