2017-10-05 129 views
1

我有以下查询来检索自定义Moodle插件中的学术顾问。为什么我的Moodle查询在“Ad hoc数据库查询”中工作,但不在我的插件中?

这里定义的学术顾问的角色配置:https://docs.moodle.org/en/Parent_role

我在特设数据库运行查询(和MySQL工作台),并在这两个的工作正常,但对于一些奇怪的因为它在我的插件中不起作用。

db_update.php

function get_academic_advisees($userid) { 
    global $DB; 

    $sql = 'SELECT child.username, child.firstname, child.lastname 
      FROM {user} user 
      JOIN {role_assignments} ra ON ra.userid = user.id 
      JOIN {role} role ON role.id = ra.roleid 
      JOIN {context} ctx ON ctx.id = ra.contextid 
      AND ctx.contextlevel = 30 
      JOIN {user} child ON child.id = ctx.instanceid 
      WHERE role.shortname = "academic_adviser" 
      and user.username = ?'; 

    return $DB->get_records_sql($sql, array($userid)); 
} 

在我attendance_form.php页,其中包括在attendance.php(它调用db_update.php):

require_once("{$CFG->libdir}/formslib.php"); 

class attendance_form extends moodleform { 

    function definition() { 
     $mform =& $this->_form; 

     $mform->addElement('html', '<h2>' . get_string('attendance', 'local_attendance') . '</h2>'); 
     $mform->addElement('html', '<p>This report allows you to retrieve attendance data for your academic advisees.</p>'); 

     //$mform->addElement('text', 'student_number', get_string('student_number', 'local_attendance')); 
     global $USER; 
     $userid = $USER->id; 
     $myAdvisees = array(); 
     $adviseeArray = array(); 
     $myAdvisees = get_academic_advisees($userid); 
     foreach($myAdvisees as $myAdvisee) { 
      $key = $myAdvisee->username; 
      $value = $myAdvisee->firstname . $myAdvisee->lastname . '(' . $myAdvisee->username . ')'; 
      $adviseeArray[$key] = $value; 
     } 

     $mform->addElement('select', 'student_number', get_string('student_number', 'local_attendance'), $adviseeArray); 

     $this->add_action_buttons(true, get_string('save', 'local_attendance')); 
    } 
} 

回答

2

该函数设置了一个param '用户ID',但在查询中它试图将它与'user.username'匹配。

所以,你需要把:

$userid = $USER->username; 

如果你想让它在表单中的工作。

此外,请从$ mform = &中删除& $ this - > _ form - 很久以前Moodle停止支持PHP 4!

+0

非常感谢你 - 我是路过它$ USER-> ID,因此它应该是'和user.id =' –

0

所以正确的代码是(与感谢@davosmith):

function get_academic_advisees($userid) { 
    global $DB; 

    $sql = 'SELECT child.username, child.firstname, child.lastname 
      FROM {user} user 
      JOIN {role_assignments} ra ON ra.userid = user.id 
      JOIN {role} role ON role.id = ra.roleid 
      JOIN {context} ctx ON ctx.id = ra.contextid 
      AND ctx.contextlevel = 30 
      JOIN {user} child ON child.id = ctx.instanceid 
      WHERE role.shortname = "academic_adviser" 
      and user.id = ?'; 

    return $DB->get_records_sql($sql, array($userid)); 
} 
+1

小调 - 如果你想让它与不同的数据库后端兼容(对于核心Moodle很重要,对你的站点可能不太重要),你应该使用单引号'来包含字符串,所以应该是: role.shortname =' academic_advisor' – davosmith

+0

谢谢 - 在某些时候,我把$ sql用双引号括起来,并用单引号将字符串括起来,最后交换了它 –

相关问题