YII2 DB Count Results query

YII2 DB count results query


Simple in the controller or view file add do this:

$count=MODEL::find()    
->select(['COUNT(id) AS cnt'])    
->where([        
        'field1' => $value1,
])->
    andWhere(['>', 'field2', $value2])
->one()->cnt;

And in the model of the table add before this line:

public static function tableName()
Add public $cnt; like below:
public $cnt;
public static function tableName(){

Leave a comment

Your email address will not be published. Required fields are marked *