使用SQL取消注册类别中的Moodle用户

时间:2016-10-09 21:04:45

标签: mysql moodle

我需要取消注册所有用户一次来自所有课程的特定类别(已选择我的 moodle 网站中的名称或短名称。 我认为SQL语句是实现此目的的方法。

课程不是空的,所以删除所有课程是没有选择的。

谢谢

2 个答案:

答案 0 :(得分:1)

我没有测试过以下解决方案,但它应该产生预期的效果:

require($CFG->libdir . '/coursecatlib.php');
require($CFG->libdir . '/enrollib.php');

$categoryid = 0;    // Replace with the desired category ID.
$category = coursecat::get($categoryid);
foreach ($category->get_courses() as $course) {
    // Simulates the deletion of the course, a better solution is to copy
    // the logic from `enrol_course_delete` here directly.
    enrol_course_delete($course);
}

上面的脚本可能需要一段时间,因此您可能应该从命令行执行此操作。

您可以使用以下方式遍历子类别:

$categories = $category->get_children();
foreach ($categories as $category) {
}

要按短名称获取类别的ID,请使用以下命令:

$name = "My category";
$categoryid = $DB->get_field('course_categories', 'id', array('name' => $name), MUST_EXIST);

请注意,类别可以使用相同的名称,您应该使用类别idnumber

答案 1 :(得分:1)

通过SQL执行此操作会非常复杂,因为有很多注册插件。每个人都有自己的数据集。

如果您查看function reset_course_userdata中的/lib/moodlelib.php,则会显示此部分代码。尝试根据需要修改它。

$plugins = enrol_get_plugins(true);
$instances = enrol_get_instances($data->courseid, true);
foreach ($instances as $key => $instance) {
    if (!isset($plugins[$instance->enrol])) {
        unset($instances[$key]);
        continue;
    }
}

foreach ($data->unenrol_users as $withroleid) {
    if ($withroleid) {
        $sql = "SELECT ue.*
                  FROM {user_enrolments} ue
                  JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
                  JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
                  JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
        $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);

    } else {
        // Without any role assigned at course context.
        $sql = "SELECT ue.*
                  FROM {user_enrolments} ue
                  JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
                  JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
             LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
                 WHERE ra.id IS null";
        $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
    }

    $rs = $DB->get_recordset_sql($sql, $params);
    foreach ($rs as $ue) {
        if (!isset($instances[$ue->enrolid])) {
            continue;
        }
        $instance = $instances[$ue->enrolid];
        $plugin = $plugins[$instance->enrol];
        if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
            continue;
        }

        $plugin->unenrol_user($instance, $ue->userid);
        $data->unenrolled[$ue->userid] = $ue->userid;
    }
    $rs->close();
}