Answer the question
In order to leave comments, you need to log in
How to count the number of records using ActiveQuery?
There is an employees
table , it has a department_id field . The relationship is declared in the Employees model :
public function getDepartment()
{
return $this->hasOne(Management::className(), ['id' => 'department_id']);
}
SELECT `management`.`value`, COUNT(*) FROM `employees` LEFT JOIN `management` ON `employees`.`department_id` = `management`.`id` GROUP BY `employees`.`department_id`
ArrayHelper::map(Employees::find()
->select(['COUNT(*) AS count', 'value'])
->joinWith('department')
->groupBy('department_id')
->createCommand()
->queryAll(), 'value', 'count');
Answer the question
In order to leave comments, you need to log in
Try like this:
Employees::find()
->select(['COUNT(*) AS depcount'])
->joinWith('department')
->groupBy('department_id')
->all();
Employees::find()
->select(['COUNT(*) AS depcount'])
->joinWith('department')
->groupBy('department_id')
->createCommand()
->queryAll();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question