Search code examples
phpmysqlmoodlemoodle-api

I want to retrieve the instance of a course module


tl;dr; trying to get a course module instance via a course module through mysql or the official moodle api. My solution in the end seems rather scrappy though, so i would like some advice.

Hi Moodle people

I am trying to retrieve the corresponding course module instance for each row in mdl_course_modules, a instance in this context would be a single row from mdl_quiz, mdl_wiki or some other course_modules instance.

I have tried a few things, the one i expected to work was:

function get_all_course_modules($course_id) {
   global $DB;
   $course = $DB->get_record('course', array('id' => $course_id));
   $mod_info = get_fast_modinfo($course);
}

I wasn't able to get the course modules instance from $mod_info .

So i tried to do some custom mysql instead,

SELECT course.id, course.fullname, cm.course, cm.section, m.name 
 FROM mdl_course AS course 
 JOIN mdl_course_modules AS cm ON cm.course = course.id
 JOIN mdl_modules AS m ON m.id = cm.module 
 JOIN CONCAT('mdl_', m.name) AS module_type ON ...somethingsomething
 WHERE course.id = 2;

The sql isn't quite finished, i stumbled on the fact that i dont know all of the different course modules beforehand, that means that i have to use the name of the course_module dynamically to select which instance table i want to join on, or just LEFT JOIN on all of the possible course modules instance tables, but that would take forever and would stop working if someone put in a new course module instance.

Right now im doing the following:

 $result = array();
$course_mods = get_course_mods($course_id);

if($course_mods) {
    foreach($course_mods as $course_mod) {
        $DB->get_records_sql('some sql that selects the instance');
    }
}

return $result;

This last piece of code would eventually work, i would be able to able to dynamically create the query from the $course_mod variables such as $course_mod->instance, $course_mod->mod_name etc.

But i think this seems tough. Have any of you guys suceeded in getting the course_module instance in a easier way??

Thanks!!


Solution

  • This is the function i ended up using, to retrieve course module instances, its not so pretty, but whatever.

    function get_all_course_modules($course_id) {
    global $DB;
    $course_mods = get_course_mods($course_id);
    $result = array();
    if($course_mods) {
        foreach($course_mods as $course_mod) {
            $course_mod->course_module_instance = $DB->get_record($course_mod->modname, array('id' =>$course_mod->instance ));
            $result[$course_mod->id] = $course_mod;
        }
    }
    return $result;
    }