0

I want to get the users per category. I'm using moodle 3.8 version. is there any method for get the users by category.

Muditha
  • 173
  • 1
  • 2
  • 12
  • 1
    It isn't clear what your question means. Are you asking for a list of users who are assigned a role at the category level? Or a list of users who are assigned a role at any context (category / course / activity / block) within that category? Are you interested in specific roles or just a list of all users with any role at all? – davosmith Apr 18 '22 at 08:43
  • Sorry for that. i actually want to get list of users according to the category. As an example, if i have course with this path "Bachelor/Management/2018/intake 1" and like wise imagine there are students year by year (Ex: 2019, 2020). Now if i want to get management students, the function should be return all students (users) in every year. i think now clear my problem to you. – Muditha Apr 18 '22 at 08:58
  • 1
    So you want everyone with a "student" role assigned at the course level for any course found in the given category or one of its subcategories? – davosmith Apr 18 '22 at 13:32
  • yes it is correct – Muditha Apr 19 '22 at 04:30

1 Answers1

1

If you're looking for Moodle functions to do this, then you could probably call:

$cat = core_course_category::get($categoryid);
$courseids = $cat->get_courses(['recursive', 'idonly']);
$userids = [];
foreach ($courseids as $courseid) {
    $context = context_course::instance($courseid);
    $courseusers = get_enrolled_users($context, '', 0, 'u.id');
    $userids = array_merge($userids, array_keys($courseusers));
}

This is, however, horribly inefficient - you'd be best off writing a custom SQL query that, given the list of course ids, will generate a list of enrolled users for all of those courses (take a look inside the code of get_enrolled_users() to see how to build such an SQL query).

davosmith
  • 6,037
  • 2
  • 14
  • 23