Paged db_select() in Drupal 8

Public

This is an example how paged db_select() can be done in Drupal 8. Taken from this article by Chris Hall: http://running-on-drupal8.co.uk/blog/paging-dbselects-drupal8

</> CopyGet raw version
php
  1. function blog_page_last() {
  2.  
  3. $build = array();
  4.  
  5. $query = db_select('node_field_data', 'n');
  6. $query->addTag('node_access');
  7. $query->condition('type','blog');
  8. $query->condition('status',1);
  9.  
  10. $count_query = clone $query;
  11. $count_query->addExpression('Count(n.nid)');
  12.  
  13. $paged_query = $query->extend('Drupal\Core\Database\Query\PagerSelectExtender');
  14. $paged_query->limit(Drupal::config('node.settings')->get('items_per_page'));
  15. $paged_query->setCountQuery($count_query);
  16.  
  17. $nids = $paged_query
  18. ->fields('n', array('nid', 'sticky', 'created'))
  19. ->orderBy('sticky', 'DESC')
  20. ->orderBy('created', 'DESC')
  21. ->execute()
  22. ->fetchCol();
  23.  
  24. if (!empty($nids)) {
  25. $nodes = node_load_multiple($nids);
  26. $build['nodes'] = node_view_multiple($nodes);
  27. $build['pager'] = array(
  28. '#theme' => 'pager',
  29. '#weight' => 5,
  30. );
  31. }
  32. else {
  33. drupal_set_message(t('No blog entries have been created.'));
  34. }
  35. drupal_add_feed('blog/feed', t('RSS - blogs'));
  36.  
  37. return $build;
  38. }