D8 里有两种数据查询:一种是利用 db_query 直接对数据库表操作,一种是采用 entityTypeManager 进行实体操作。
两种方式的分页处理略有不同,在实际应用中可以灵活使用。下面是两个实例展示:
第一种,db_query 方式:
example
public static function someAdminTable() {
$limit = 50;
if (empty($_REQUEST['page'])) {
$start = 0;
}
else {
$start = $_REQUEST['page'] * $limit;
}
$table = 'some_table';
$query = 'SELECT * FROM {' . $table . '}';
$count_query = 'SELECT count(*) FROM {' . $table . '}';
$count_result = db_query($count_query);
$count_result->allowRowCount = TRUE;
$total_count = $count_result->fetchAssoc();
$total = $total_count['count'];
$page = pager_default_initialize($total, $limit);
$query_items = db_query_range($query, $start, $limit);
$query_items->allowRowCount = TRUE;
if ($query_items->rowCount() == 0) {
return t('No Results found yet Please import');
}
else {
$header = array('accreditation_id',
'surname',
'first_name',
'email',
'type',
'Edit',
);
$rows = array();
foreach ($query_items as $key) {
if ($key->accreditation_id == 12399) {
// dsm($key); .
}
$the_link_path = 'admin/config/something/some-settings/edit/' . $key->accreditation_id;
$link = custom_l(t('edit'), $the_link_path); // See Note
$rows[] = array(
$key->accreditation_id,
$key->surname,
$key->first_name,
$key->email,
$key->type,
$link,
);
}
}
$render = [];
$render[] = array(
'#type' => 'table',
'#header' => $header,
'#rows' => $rows,
'#attributes' => array(
'id' => 'foo',
),
);
$render[] = ['#type' => 'pager'];
$markup = drupal_render($render);
return $markup;
}
// custom_l
function custom_l($text, $the_link_path) {
$link_generator = \Drupal::service('link_generator');
$installer_url = \Drupal\Core\Url::fromUri('base://'. $the_link_path );
$link = $link_generator->generate($text, $installer_url);
return $link;
}
第二种,entityTypeManager 方式:
$limit = 3; //每页显示数量 值为false将全部显示
$storage = \Drupal::entityTypeManager()->getStorage('node');
$query = $storage->getQuery();//获取实体查询对象
$query->sort('changed', 'DESC');//按时间倒序显示,最新的在最前
$query->currentRevision(); //仅选择每个实体的当前版本
$query->condition('status', \Drupal\node\NodeInterface::PUBLISHED);//仅显示发布的内容
//显示什么取决于这里设置的条件,更多请参考本系列实体查询主题
if ($limit) {
$query->pager($limit);
}
$entity_ids = $query->execute();
$entities = $storage->loadMultiple($entity_ids);
$viewBuilder = \Drupal::entityTypeManager()->getViewBuilder('node');
$build['nodes'] = $viewBuilder->viewMultiple($entities, 'teaser'); //构建摘要列表视图
if ($limit) {
$build['pager'] = [
'#type' => 'pager', //构建分页器
];
}
return $build;