Skip to content

Commit

Permalink
MDL-51241 cohorts: Update to cohort query.
Browse files Browse the repository at this point in the history
This improves the speed of returning a list of
cohorts. Thanks to François Gannaz for providing
this patch.
  • Loading branch information
abgreeve committed Sep 17, 2015
1 parent d230899 commit de66dde
Showing 1 changed file with 19 additions and 10 deletions.
29 changes: 19 additions & 10 deletions cohort/lib.php
Original file line number Diff line number Diff line change
Expand Up @@ -256,15 +256,17 @@ function cohort_get_available_cohorts($currentcontext, $withmembers = 0, $offset
$groupbysql = '';
$havingsql = '';
if ($withmembers) {
$groupbysql = " GROUP BY $fieldssql";
$fieldssql .= ', s.memberscnt';
$subfields = "c.id, COUNT(DISTINCT cm.userid) AS memberscnt";
$groupbysql = " GROUP BY c.id";
$fromsql = " LEFT JOIN {cohort_members} cm ON cm.cohortid = c.id ";
$fieldssql .= ', COUNT(DISTINCT cm.userid) AS memberscnt';
if (in_array($withmembers,
array(COHORT_COUNT_ENROLLED_MEMBERS, COHORT_WITH_ENROLLED_MEMBERS_ONLY, COHORT_WITH_NOTENROLLED_MEMBERS_ONLY))) {
list($esql, $params2) = get_enrolled_sql($currentcontext);
$fromsql .= " LEFT JOIN ($esql) u ON u.id = cm.userid ";
$params = array_merge($params2, $params);
$fieldssql .= ', COUNT(DISTINCT u.id) AS enrolledcnt';
$fieldssql .= ', s.enrolledcnt';
$subfields .= ', COUNT(DISTINCT u.id) AS enrolledcnt';
}
if ($withmembers == COHORT_WITH_MEMBERS_ONLY) {
$havingsql = " HAVING COUNT(DISTINCT cm.userid) > 0";
Expand All @@ -280,13 +282,20 @@ function cohort_get_available_cohorts($currentcontext, $withmembers = 0, $offset
$params = array_merge($params, $searchparams);
}

$sql = "SELECT $fieldssql
FROM {cohort} c
$fromsql
WHERE $wheresql
$groupbysql
$havingsql
ORDER BY c.name, c.idnumber";
if ($withmembers) {
$sql = "SELECT " . str_replace('c.', 'cohort.', $fieldssql) . "
FROM {cohort} cohort
JOIN (SELECT $subfields
FROM {cohort} c $fromsql
WHERE $wheresql $groupbysql $havingsql
) s ON cohort.id = s.id
ORDER BY cohort.name, cohort.idnumber";
} else {
$sql = "SELECT $fieldssql
FROM {cohort} c $fromsql
WHERE $wheresql
ORDER BY c.name, c.idnumber";
}

return $DB->get_records_sql($sql, $params, $offset, $limit);
}
Expand Down

0 comments on commit de66dde

Please sign in to comment.