DRUPAL8模块开发 - DRUPAL8数据库API - 结果集

翻译者:长风Drupal开发团队(成都长风云信息技术有限公司)

 

Drupal8或者Drupal7的选择查询将始终返回一个零或多个记录的结果集对象。根据用例,在Drupal开发过程中有几种方法可以从结果集检索数据。最常见的情况是用 foreach()循环迭代结果集
$result = $connection->query("SELECT field1, field2 FROM {mytable}");
foreach ($result as $record) {
// Do something with each $record
}
然而,根据需要的结果,还有许多其他方法来检索记录。

若要显式获取下一条记录,请使用:
$record = $result->fetch();  // Use the default fetch mode.
$record = $result->fetchObject();  // Fetch as a stdClass object.
$record = $result->fetchAssoc(); // Fetch as an associative array.
如果没有下一条记录,将返回false。fetch()函数通常应避免使用fetchObject() 和fetchAssoc(),因为后者更为自文档化。如果需要使用其他PDO支持的获取模式,则使用fetch()。

若要从结果集中取出单个字段,请使用:对于第一个字段,$CulnNoX索$record = $result->fetchField($column_index);
对于第一个字段,$column_index索引的默认值为0。

要计算删除、插入或更新语句返回的行数,请使用:
$number_of_rows = $result->rowCount();
使用SELECT语句返回的行数进行计数:
$number_of_rows = $connection->select('mytable')->countQuery()->execute()->fetchField();
若要立即将所有记录提取到单个数组中,请使用下列之一:
// Retrieve all records into an indexed array of stdClass objects.
$result->fetchAll();
// Retrieve all records into an associative array keyed by the field in the result specified.
$result->fetchAllAssoc($field);
// Retrieve a 2-column result set as an associative array of field 0 => field 1.
$result->fetchAllKeyed();
// You can also specify which two fields to use by specifying the column numbers for each field
$result->fetchAllKeyed(0,2); // would be field 0 => field 2
$result->fetchAllKeyed(1,0); // would be field 1 => field 0
// If you need an array where keys and values contain the same field (e.g. for creating a 'checkboxes' form element), the following is a perfectly valid method:
$result->fetchAllKeyed(0,0); // would be field 0 => field 0, e.g. [article] => [article]
// Retrieve a 1-column result set as one single array.
$result->fetchCol();
// Column number can be specified otherwise defaults to first column
$result->fetchCol($column_index);
注意,fetchAll() 和 fetchAllAssoc() 将默认地使用在查询(数字数组、关联数组或对象)上设置的任何获取模式来获取。可以通过传递新的获取模式常数来修改。对于fetchAll(),它是第一个参数。对于 fetchAllAssoc(),它是第二个参数。实例:
// Get an array of arrays keyed on the field 'id'.
$result->fetchAllAssoc('id', PDO::FETCH_ASSOC);
// Get an array of arrays with both numeric and associative keys.
$result->fetchAll(PDO::FETCH_BOTH);
因为PHP支持返回对象上的链接方法调用,所以完全跳过$result变量是非常常见的,例如:
// Get an associative array of ids to titles.
$examples = $connection->query("SELECT id, title FROM {mytable}")->fetchAllKeyed();
// Get a single record out of the database.
$myobj = $connection->query("SELECT * FROM {mytable} WHERE example = :example", [':example' => $example])->fetchObject();
// Get a single value out of the database.
$myval = $connection->query("SELECT example FROM {mytable} WHERE id = :id", [':id' => $id])->fetchField();
如果你想要的是一个简单的数组,比如[1, 2, 3,4, 5 ],你将不得不解决一些更像[ 1=1, 2=>2, 3=> 3, 4=>4, 5=>5 ]的问题。你可以通过使用
$ids = $connection->query("SELECT id FROM {example}")->fetchAllKeyed(0,0);