I was looking for the proper SQL queries for retrieving all students enrolled in a certain course, or all courses a certain student has enrolled in, on Moodle
In the case of need the count of the enrolled students for a course. It may be achieved simply using the enrollment api. The secret key here is supplying withcapability
parameter to the count_enrolled_users()
function that only the Student
role has. For example:
$context = context_COURSE::instance($course->id);
count_enrolled_users($context,'mod/assignment:submit')
Here mod/assignment:submit
is a capability that only student able to do, so the returned int number will not include other common roles such as Teachers enrolled in the course.
I have used the above code for Moodle 3.1 in theme renderer.php
to show the enrolled students count for each course in the courses list at the front page.