Moodle:データ操作APIデータベース操作
Moodle Data Manipulation Api Database Operations
主な情報
重要な注意点: このページに表示されているすべての機能は、 Moodle2.0以上 、変更した場所 DBレイヤー いくつかの新機能をサポートします。以前のMoodleバージョンの情報が必要な場合は、 DML関数-2.0より前 ページ。変更の詳細については、以下を参照してください。 移行ドキュメント 。
- このページのすべての関数呼び出しは$ DBグローバルオブジェクトのパブリックメソッドであるため、関数内で「インポート」する必要があります(グローバルスクリプトでは必要ありません)。
global $DB
- $ DBグローバルオブジェクトは、で定義されているmoodle_databaseクラスのインスタンスです。 moodle_database.php
- 関数内のすべての$ tableパラメーターは、テーブル名であることが意図されています なし プレフィックス。
$user = $DB->get_record('user', array('id'=>'1'))
- xxx_sql()関数を使用する場合、テーブル名は中括弧で囲む必要があります。
$user = $DB->get_record_sql('SELECT * FROM {user} WHERE id = ?', array(1))
- 関数内のすべての$ conditionsパラメーターは、fieldname => fieldvalue要素の配列です。
$user = $DB->get_record('user', array('firstname'=>'Martin', 'lastname'=>'Dougiamas'))
- 関数内のすべての$ paramsパラメーターは、SQLステートメントのプレースホルダーを埋めるために使用される値の配列です。疑問符と名前付きプレースホルダーの両方を使用できます。名前付きパラメータに注意してください 一意である必要があります 渡された値が同じであっても。
/// 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'))
機能
単一のレコードを取得する
$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列」が含まれていることを確認することがベストプラクティスのようです。 (カスタムテーブルを開発するときは、この理由からidを最初の列にしてください!)
$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.
連想配列のキー/値ペアとしてデータを取得する
$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.
特定の基準に一致するレコードの数を確認する
$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つのレコードが存在するかどうかを確認する
$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.
例
moodle_database :: get_records()
指定されたすべての条件が満たされたオブジェクトの配列として、いくつかのレコードを取得します。
///Get all records where foo = bar $result = $DB->get_records($table,array('foo'=>'bar')) ///Get all records where foo = bar and jon = doe $result = $DB->get_records($table,array('foo' => 'bar' , 'jon' => 'doe')) ///Get all records where foo = bar, but only return the fields foo,bar,jon,doe $result = $DB->get_records($table,array('foo'=>'bar'),null,'foo,bar,jon,doe') ///The previous example would cause data issues unless the 'foo' field happens to have unique values.
moodle_database :: get_records_select()
特定のWHERE句に一致するオブジェクトの配列として多数のレコードを取得します。配列キーはオブジェクトのIDになるため、キーが0の最初のアイテムに依存してはならないことに注意してください。
///Get all records where jon = 'doe' and bob is not = 'tom' ///The 'select' parameter is (if not empty) is dropped directly into the WHERE clause without alteration. $table = 'foo' $select = 'jon = 'doe' AND bob 'tom'' //is put into the where clause $result = $DB->get_records_select($table,$select)
moodle_database :: get_records_sql()
SQLステートメントを使用して、オブジェクトの配列として多数のレコードを取得します。 moodle_databaseで抽象関数として定義されているこのメソッドは、データベースタイプごとに実装されます。
///Get all records from 'table' where foo = bar $result = $DB->get_records_sql('SELECT * FROM {table} WHERE foo = ?', array('bar')) ///Get all records from 'table' where foo = 'bar' and bob = 'tom' ///This is somewhat similar to how Drupal makes its queries $result = $DB->get_records_sql('SELECT * FROM {table} WHERE foo = ? AND bob = ?', array( 'bar' , 'tom' ))
moodle_database :: get_records_list()
1つのフィールドが1つの値のリストと一致するオブジェクトの配列として、いくつかのレコードを取得します。
///Get all records where the values('bar', 'elephant', 'moodle') are found in the field 'foo' $result = $DB->get_records_list($table, 'foo', array( 'bar', 'elephant', 'moodle')) ///Get all records where the values('bar', 'elephant', 'moodle') are found in the field 'foo' ///Only returning the fields 'id', 'test' and 'taco' $result = $DB->get_records_list($table, 'foo', array( 'bar', 'elephant', 'moodle'), null, 'id,test,taco')
moodle_database :: get_records_menu()
指定されたすべての条件が満たされた連想配列として、いくつかのレコードから最初の2つの列を取得します。 2つのフィールドを選択するか、パラメーターを空白のままにすると、メソッドはテーブルの最初の2列を返します。連想配列を返します。
///Get all records from table 'foo' where column 'foo' is equal to the value 'bar' $table = 'foo' ///name of table $conditions = array('foo'=>'bar') ///the name of the field (key) and the desired value $result = $DB->get_records_menu($table,$conditions)) ///Get all records from table 'foo' where column 'foo' is equal to the value 'bar' ///Returning the values from the columns 'id' and 'tacos' $table = 'foo' ///name of table $conditions = array('foo'=>'bar') ///the name of the field (key) and the desired value $sort = 'id' //field or fields you want to sort the result by $fields = 'id, tacos' ///list of fields to return $result = $DB->get_records_menu($table,$conditions,$sort,$fields)) //If you do not specify $fields, the first two columns of the table will be returned
この最後の例の結果は次のようになります。
/// The value of the id field is 909 and the value of the 'tacos' column is 6 array(1) { [909]=6 }
moodle_database :: get_records_select_menu()
特定のWHERE句に一致する連想配列として、いくつかのレコードから最初の2列を取得します。
///Get all records where jon = 'doe' and bob is not = 'tom' ///The 'select' parameter is (if not empty) is dropped directly into the WHERE clause without alteration. $table = 'foo' $select = 'jon = 'doe' AND bob != 'tom' ' //is put into the where clause $result = $DB->get_records_select_menu($table,$select) $table = 'foo' $select = 'jon = 'doe' AND bob != 'tom' ' //is put into the where clause $params = null $fields = 'id, tacos'//return these fields $sort = 'id' //field or fields you want to sort the result by $result = $DB->get_records_select_menu($table,$select,$params,$sort,$fields)
この最後の例の結果は次のようになります。
/// The value of the id field is 909 and the value of the 'tacos' column is 6 array(1) { [909]=6 }
moodle_database :: get_records_sql_menu()
SQLステートメントを使用して、多数のレコードから最初の2列を連想配列として取得します。
///Get all records from table foo where bar = 6 $sql = 'SELECT * FROM foo WHERE bar = ?' $params = array(6) $result = $DB->get_records_sql_menu($sql,$params) ///Get all records from table foo where bar = 6 $sql = 'SELECT id,tacos FROM foo WHERE bar = ?' $params = array(6) $result = $DB->get_records_sql_menu($sql,$params)
この最後の例の結果は次のようになります。
/// The value of the id field is 909 and the value of the 'tacos' column is 6 array(1) { [909]=6 }
1つのレコードから特定のフィールド値を取得する
$DB->get_field($table, $return, array $conditions, $strictness=IGNORE_MISSING) /// Get a single field value from a table record 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_field_select($table, $return, $select, array $params=null, $strictness=IGNORE_MISSING) /// Get a single field value from a table record which match a particular WHERE clause. $DB->get_field_sql($sql, array $params=null, $strictness=IGNORE_MISSING) /// Get a single field value (first field) using a SQL statement.
さまざまなレコードから特定のフィールド値を取得する
$DB->get_fieldset_select($table, $return, $select, array $params=null) /// Selects records and return values of chosen field as an array which match a particular WHERE clause. $DB->get_fieldset_sql($sql, array $params=null) /// Selects records and return values (first field) as an array using a SQL statement.
データベースに特定のフィールドを設定する
$DB->set_field($table, $newfield, $newvalue, array $conditions=null) /// Set a single field in every table record where all the given conditions met. $DB->set_field_select($table, $newfield, $newvalue, $select, array $params=null) /// Set a single field in every table record which match a particular WHERE clause.
レコードの削除
$DB->delete_records($table, array $conditions=null) /// Delete the records from a table where all the given conditions met. $DB->delete_records_select($table, $select, array $params=null) /// Delete one or more records from a table which match a particular WHERE clause.
レコードの挿入
レコードを挿入するメソッドは、適切にinsert_record()と呼ばれます。このメソッドは4つのパラメーターを受け入れますが、ほとんどの実装では4番目の「バルク」は使用されていません。
$DB->insert_record($table, $dataobject, $returnid=true, $bulk=false) /// Insert a record into a table and return the 'id' field if required.
例
$record = new stdClass() $record->name = 'overview' $record->displayorder = '10000' $DB->insert_record('quiz_report', $record, false) $record = new stdClass() $record->name = 'overview' $record->displayorder = '10000' $lastinsertid = $DB->insert_record('quiz_report', $record)
レコードの更新
$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」メソッドを使用できます。これ以上具体的なものが機能しない場合にのみこれを使用してください
$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.
レコードセットの使用
DBから取得するレコードの数が多い場合、 get_records_xxx() 上記の関数は、メモリ内のすべてのレコードを同時にロードするため、最適とは言えません。そのような状況では、これらを使用することを強くお勧めします get_recordset_xxx() 代わりに、1つの優れたメカニズムを使用してすべてのターゲットレコードを反復処理し、大量のメモリを節約する関数。
たった一つのことは 絶対に重要 :レコードセットを使用した後は、レコードセットを閉じることを忘れないでください。 (これにより、RDBMSの多くのリソースが解放されます)。
これは、を使用してレコードを反復処理する一般的な方法です。 get_recordset_xxx() 機能:
$rs = $DB->get_recordset(....) { foreach ($rs as $record) { // Do whatever you want with this record } $rs->close() // Don't forget to close the recordset!
そして、これは利用可能な関数のリストです(上記のget_records_xxx()と100%ペアになっています):
$DB->get_recordset($table, array $conditions=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) /// Get a number of records as a moodle_recordset where all the given conditions met. $DB->get_recordset_select($table, $select, array $params=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) /// Get a number of records as a moodle_recordset which match a particular WHERE clause. $DB->get_recordset_sql($sql, array $params=null, $limitfrom=0, $limitnum=0) /// Get a number of records as a moodle_recordset using a SQL statement. $DB->get_recordset_list($table, $field='', $values='', $sort='', $fields='*', $limitfrom='', $limitnum='') /// Get a number of records as a moodle_recordset where one field matches one list of values.
get_record関数とは異なり、$ rs == trueまたは!empty($ rs)を使用して、レコードが見つかったかどうかを判別することはできません。レコードセットは、標準のPHPイテレータインターフェイスを実装します( http://uk.php.net/manual/en/class.iterator.php )。
そう、
if ($rs->valid()) { // The recordset contains records. }
委任されたトランザクション
- 一部のデータベース(MyISAM MySQLデータベースエンジンなど)はトランザクションをサポートしていませんが、すべてのサーバー管理者は、トランザクションをサポートするデータベース(InnoDB MySQLデータベースエンジンなど)に移行することを強くお勧めします。
- 以前のバージョンは、1レベルのトランザクションのみをサポートしていました。 Moodle 2.0以降、DMLレイヤーはトランザクションのネストを可能にする委任されたトランザクションをエミュレートします。
- トランザクションは、Webサービス、登録、認証プラグインなどのさまざまなプラグインを対象としたMoodleコアではあまり使用しないでください。
- 一部のサブシステム(メッセージングなど)は、外部システムでロールバックできないため、トランザクションをサポートしていません。
トランザクションは次の方法で開始されます。
$transaction = $DB->start_delegated_transaction()
終了者:
$transaction->allow_commit()
通常、例外がスローされると、トランザクションはロールバックされます。 $transaction->rollback($ex)
トランザクションをサポートしていないデータベースとの互換性が損なわれる可能性があるため、慎重に使用する必要があります。トランザクションは、予想されるコードフローの一部として使用することはできず、データの整合性を緊急に保護するためにのみ使用できます。
詳細については、をご覧ください。 DBレイヤー2.0委任トランザクション または MDL-20625 。
例
global $DB try { $transaction = $DB->start_delegated_transaction() // Insert a record $DB->insert_record('foo', $object) $DB->insert_record('bar', $otherobject) // Assuming the both inserts work, we get to the following line. $transaction->allow_commit() } catch(Exception $e) { $transaction->rollback($e) }
SQL互換機能
実際のデータベース間の互換性を持たせるために、実行中のDBMoodleに基づいてSQLフラグメントを構築するために使用されるいくつかのヘルパー関数があります。それらを使用して、あちこちで条件付きクエリを回避し、それらの「非互換性」を永久に修正します。
$DB->sql_bitand($int1, $int2) /// Returns the SQL text to be used in order to perform one bitwise AND /// operation between 2 integers. $DB->sql_bitnot($int1) /// Returns the SQL text to be used in order to perform one bitwise NOT /// operation with 1 integer. $DB->sql_bitor($int1, $int2) /// Returns the SQL text to be used in order to perform one bitwise OR /// operation between 2 integers. $DB->sql_bitxor($int1, $int2) /// Returns the SQL text to be used in order to perform one bitwise XOR /// operation between 2 integers. $DB->sql_null_from_clause() /// Returns the FROM clause required by some DBs in all SELECT statements. $DB->sql_ceil($fieldname) /// Returns the correct CEIL expression applied to fieldname. $DB->sql_like($fieldname, $param, $casesensitive = true, $accentsensitive = true, $notlike = false, $escapechar = ' \ ') /// Returns the proper SQL to do LIKE. For example: $DB->get_records_sql('SELECT ... WHERE '.$DB->sql_like('idnumber', ':idnum').' ... ', array( 'idnum' => 'foo')) /// Note: Use $DB->sql_like_escape(...) when its user input from a form. $DB->sql_length($fieldname) /// Returns the SQL text to be used to calculate the length in characters of one expression. $DB->sql_modulo($int1, $int2) /// Returns the SQL text to be used in order to calculate module - remainder after division $DB->sql_position($needle, $haystack) /// Returns the SQL for returning searching one string for the location of another. /// Note: If using placeholders BOTH in $needle and $haystack, they MUST be named placeholders. $DB->sql_substr($expr, $start, $length=false) /// Returns the proper substr() SQL text used to extract substrings from DB. /// Note: This fuction has changed in Moodle 2.0 and now at least 2 params are mandatory. /// Note: Now it returns the whole SQL text to be used instead of only the function name. $DB->sql_cast_char2int($fieldname, $text=false) /// Returns the SQL to be used in order to CAST one CHAR column to INTEGER. $DB->sql_cast_char2real($fieldname, $text=false) /// Returns the SQL to be used in order to CAST one CHAR column to REAL number. $DB->sql_compare_text($fieldname, $numchars=32) /// Returns the SQL text to be used to compare one TEXT (clob) column. /// with one VARCHAR column. $DB->sql_order_by_text($fieldname, $numchars=32) /// Returns the SQL text to be used to order by one TEXT (clob) column. $DB->sql_concat() /// Returns the proper SQL to do CONCAT between the elements passed. $DB->sql_concat_join($separator='' '', $elements=array()) /// Returns the proper SQL to do CONCAT between the elements passed using one separator. $DB->sql_fullname($first='firstname', $last='lastname') /// Returns the proper SQL to concatenate $firstname and $lastname. $DB->sql_isempty($tablename, $fieldname, $nullablefield, $textfield) /// Returns the proper SQL to know if one field is empty. $DB->sql_isnotempty($tablename, $fieldname, $nullablefield, $textfield) /// Returns the proper SQL to know if one field is not empty. $DB->sql_empty() /// Returns the empty string char used by every supported DB.
機能をデバッグする
実行した場合
$DB->set_debug(true)
次に、$ DBは、タイミング情報とともに、実行されたすべてのクエリのSQLを出力します。これは、コードをデバッグするときに役立ちます。明らかに、統合のためにコードを送信する前に、このような呼び出しをすべて削除する必要があります。
特殊なケース
get_course
Moodle 2.5.1以降、IDに基づいてコースレコードを取得する場合、特にコースが存在する可能性が高い場合は、get_record( 'course'、...)を使用する代わりにget_course関数を使用する必要があります。取得されるのは、ページの現在のコースまたはサイトコースのいずれかです。これらの2つのコースレコードはおそらくすでにロードされており、この関数を使用するとデータベースクエリが保存されます。
もう1つの利点として、コードが短くて読みやすくなっています。
交換:
$course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST)
と:
$course = get_course($courseid)
も参照してください
- SQLコーディングスタイル
- コアAPI
- DML例外 :新しいDMLコードは、問題が発生した場合にfalseを返すのではなく、例外をスローします
- DMLドライバー :新しいDMLレイヤーのデータベースドライバー
- DML関数-2.0より前 : (非推奨です!) Moodle2.0より前に有効な情報について。
- DDL関数 :DBオブジェクトの処理に使用されるすべての関数( DDL )が定義されています。
- DBレイヤー2.0の例 :さまざまなDML関数を使用したいくつかのコード例を参照してください。
- DBレイヤー2.0移行ドキュメント :新しいMoodle2.0DBレイヤーで動作するようにコードを変更する方法に関する情報。
- DTL機能 :SQLデータベースに保存されているデータのエクスポート、インポート、移動