Association Cakephp 3 上的简单计数和排序

Simple Count and Sort on Association Cakephp 3

我有学生 table 和成绩 table。学生有很多结果。结果仅与一名学生相关联。所以我想要实现的是这样的:

$this->Students
    ->find('all')
    ->contain('Results')
    ->order('by count of results each student has' => 'asc');

如有任何帮助,我们将不胜感激。

试试这个

$query = $this->Students->find()
    $query->select(['total_result'=> $query->func()->count('Results.id')])
    ->autoFields(true)
    ->contain('Results')
    ->leftJoinWith('Results')
    ->group(['Students.id'])
    ->order(['total_result'=>'ASC']);

debug($query->all());

更多检查Here