Moodle API文档 —— Data manipulation API

moodle的Data manipulation API中介绍了用于访问数据库的一些函数。你应该仅通过使用这些函数来进行数据库操作,因为这些函数对数据库操作进行了抽象,并保证这些操作会在不同的DBMS上正常执行。

概述

所有的涉及到数据操纵的函数都是全局对象$DB的公共方法。因此首先你需要“导入”这个全局对象:

1
global $DB;
  • 全局对象$DB是一个moodle_database类的对象,这个类定义在moodle_database.php中。
  • 其参数中所有的表名($table)都是不带系统默认添加的前缀的。
1
$user = $DB->get_record('user', array('id'=>'1'));
  • 在使用xxx_sql()函数时,表名必须用大括号括起来
1
$user = $DB->get_record_sql('SELECT * FROM {user} WHERE id = ?', array(1));
  • 参数中所有的条件($condition)都应以数组(域名 => 域值)的形式列出
1
$user = $DB->get_record('user', array('firstname'=>'Martin', 'lastname'=>'Dougiamas'));
  • 参数中所有的sql参数($params)都应该为sql语句,其中允许有问号和占位符。不过占位符必须是唯一的,即使两个占位符所传递的值相同。
1
2
3
4
5
6
7
/// Question mark placeholders:
$DB->get_record_sql('SELECT * FROM {user} WHERE firstname = ? AND lastname = ?',
array('Martin', 'Dougiamas'));
/// Named placeholders:
$DB->get_record_sql('SELECT * FROM {user} WHERE firstname = :firstname AND lastname = :lastname',
array('firstname'=>'Martin', 'lastname'=>'Dougiamas'));

可能用到的函数

获取一条记录

1
2
3
4
5
6
7
8
9
$DB->get_record($table, array $conditions, $fields='*', $strictness=IGNORE_MISSING)
/// Get a single database record as an object where all the given conditions met.
/// @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
/// IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
/// MUST_EXIST means throw exception if no record or multiple records found
$DB->get_record_select($table, $select, array $params=null, $fields='*', $strictness=IGNORE_MISSING)
/// Get a single database record as an object which match a particular WHERE clause.
$DB->get_record_sql($sql, array $params=null, $strictness=IGNORE_MISSING)
/// Get a single database record as an object using a SQL statement.

获取多条记录

每一个获取多条记录的函数都会返回一个数组,这个数组会以查询到的数据的第一列的值作为索引,因此在查询时请保证你要查询的表的第一列是项目id。(在创建额外的表时一定要注意这一点!)

1
2
3
4
5
6
7
8
$DB->get_records($table, array $conditions=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0)
/// Get a number of records as an array of objects where all the given conditions met.
$DB->get_records_select($table, $select, array $params=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0)
/// Get a number of records as an array of objects which match a particular WHERE clause.
$DB->get_records_sql($sql, array $params=null, $limitfrom=0, $limitnum=0)
/// Get a number of records as an array of objects using a SQL statement.
$DB->get_records_list($table, $field, array $values, $sort='', $fields='*', $limitfrom='', $limitnum='')
/// Get a number of records as an array of objects where one field match one list of values.

以键值对的形式获取数据

1
2
3
4
5
6
$DB->get_records_menu($table, array $conditions=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0)
/// Get the first two columns from a number of records as an associative array where all the given conditions met.
$DB->get_records_select_menu($table, $select, array $params=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0)
/// Get the first two columns from a number of records as an associative array which match a particular WHERE clause.
$DB->get_records_sql_menu($sql, array $params=null, $limitfrom=0, $limitnum=0)
/// Get the first two columns from a number of records as an associative array using a SQL statement.

获取查找到的数据条目数量

1
2
3
4
5
6
$DB->count_records($table, array $conditions=null)
/// Count the records in a table where all the given conditions met.
$DB->count_records_select($table, $select, array $params=null, $countitem="COUNT('x')")
/// Count the records in a table which match a particular WHERE clause.
$DB->count_records_sql($sql, array $params=null)
/// Get the result of an SQL SELECT COUNT(...) query.

检查某条记录是否存在

1
2
3
4
5
6
$DB->record_exists($table, array $conditions=null)
/// Test whether a record exists in a table where all the given conditions met.
$DB->record_exists_select($table, $select, array $params=null)
/// Test whether any records exists in a table which match a particular WHERE clause.
$DB->record_exists_sql($sql, array $params=null)
/// Test whether a SQL SELECT statement returns any records.

插入数据

insert_record()方法有四个参数。但是第四个参数”bulk”大多数情况都是不会用到的。

1
2
$DB->insert_record($table, $dataobject, $returnid=true, $bulk=false)
/// Insert a record into a table and return the "id" field if required.

在moodle2.7之后的版本中,进一步解决了批量插入”bulk”的问题。

1
2
3
4
5
6
7
8
9
10
11
12
/**
* Insert multiple records into database as fast as possible.
*
* Order of inserts is maintained, but the operation is not atomic, use transactions if necessary.
*
* This method is intended for inserting of large number of small objects, do not use for huge objects with text or binary fields.
*
* @param string $table The database table to be inserted into
* @param array|Traversable $dataobjects list of objects to be inserted, must be compatible with foreach
* @return void does not return new record ids
*/
$DB->insert_records($table, $dataobjects)

更新数据

1
2
3
4
5
6
7
8
9
10
11
12
13
$DB->update_record($table, $dataobject, $bulk=false)
/// Update a record in a table.
///
/// $dataobject is an object containing needed data
/// Relies on $dataobject having a variable "id" to
/// specify the record to update
///
/// @param string $table The database table to be checked against.
/// @param object $dataobject An object with contents equal to fieldname=>fieldvalue.
/// Must have an entry for 'id' to map to the table specified.
/// @param bool $bulk true means repeated updates expected
/// @return bool true
/// @throws dml_exception if an error occurs.

如果你需要使用sql语句执行更复杂的更新操作,你可以使用execute()函数,请尽量避免使用这个函数。

1
2
3
4
5
6
7
$DB->execute($sql, array $parms=null)
/// Executes a general sql query. Should be used only when no other method suitable.
/// Do NOT use this to make changes in db structure, use database_manager methods instead!
/// @param string $sql query
/// @param array $params query parameters
/// @return bool true
/// @throws dml_exception A DML specific exception is thrown for any errors.

使用记录集的形式访问数据

事务机制

  • 请注意一些数据库不支持事务机制(例如 MyISAM MySQL ),然而我们强烈建议将数据库部署到支持事务的数据库上(例如 InnoDB MySQL )。
  • 从moodle2.0开始,采用了DML层模拟委托事务,因此支持事务的嵌套。
  • 事务不应该在moodle核心部分被使用,它用于一些需要web服务,身份认证等功能的插件中。
  • moodle的一些子系统(例如messaging)不支持事务技术,因为它无法回滚。

一个事务的开始标志为:

1
$transaction = $DB->start_delegated_transaction();

结束标志为:

1
$transaction->allow_commit();

通常一项事务如果执行失败的话,会进行回滚:$transaction->rollback($ex);。请谨慎使用该函数,因为它在不支持事务机制的数据库中运行可能会存在一些兼容性问题。

debug函数

如果你执行$DB->set_debug(true),那么$DB会按照时间顺序输出每个查询的sql语句,这可能会对你的程序调试有些帮助。当然,最终你需要把这条语句从代码中删掉。

get_course 和 get_courses

从moodle2.5.1开始,moodle引入了一个新的函数get_course(),来替代查询课程的操作。

1
$course = get_course($courseid);

来替代

1
$course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);

另外,如果你想获取当前的所有课程,你可以直接使用get_courses()函数,不需要任何参数。

1
$courses = get_courses();