How do I do aggregate queries with CActiveRecord across several models?

Hi,

What I’d like to do is this:


(new someModel)->with('someOtherModel')

    ->toCommand()

    ->select('COUNT(*)')

    ->where('m2.field = 1')

    ->queryScalar();



But it doesn’t seem possible. The best lead I could find is CActiveRecord::query(), but there unlikely exists a method which turns relations into a command or a criteria. Correct me if I’m wrong. So the workaround must be to add a “temporary” variable to the model (//stackoverflow.com/a/12186375/52499) and:




$count = (new SomeModel)->with('someOtherModel')->find([

    'select' => 'COUNT(*) aggrColumn',

    'condition' => 'm2.field = 1'

])->aggrColumn;



Am I missing something?

hello x-yuri, one example with criteria, I hope to help you!!




$criteria = new CDbCriteria(); 	

$criteria->with=array('RelationSomeOtherModel');	

$model = Model::model()->findAllByAttributes($criteria);



For use the attributes of the relation,




$model->relationSomeOtherModel->attribute