关于Cakephp 3的简单计数和排序

时间:2017-03-23 23:36:44

标签: sorting cakephp associations cakephp-3.0 query-builder

我有学生表和结果表。学生有很多成果。结果只与一名学生有关。所以,我想要实现的是这样的:

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

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

试试这个

$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