【问题标题】:Getting total rows using Drupal 7 Database API when using limit使用限制时使用 Drupal 7 数据库 API 获取总行数
【发布时间】:2013-10-22 19:27:26
【问题描述】:

我正在使用 Drupal 7 数据库 API 来搜索我的表。我也在使用分页和排序扩展器。所以问题是,当我的查询由于分页而使用限制时,如何显示找到的记录总数?我是否需要运行具有所有条件的查询 TWICE?一次获得计数,另一次获得限制?这似乎效率低下。这是我的代码供参考。我是数据库 API 的新手,所以如果我做错了什么,请随时调整我的代码或指出正确的方向。此外,我还没有完成这个,只有一个条件,但我最终会拥有 3 个。谢谢:

function job_search() {
  // Initialising output
  $output = 'SOME STUFF';

  // Table header
  $header = array(
    array('data' => 'Description'),
    array('data' => 'Location', 'field' => 'job_location_display'),
    array('data' => 'Specialty', 'field' => 'specialty_description'),
    array('data' => 'Job Type', 'field' => 'job_board_type'),
    array('data' => 'Job Number', 'field' => 'job_number'),
  );

  // Setting the sort conditions
  if(isset($_GET['sort']) && isset($_GET['order'])) {
    // Sort it Ascending or Descending?
    if($_GET['sort'] == 'asc')
      $sort = 'ASC';
    else
      $sort = 'DESC';

    // Which column will be sorted
    switch($_GET['order']) {
      case 'Location':
        $order = 'job_location_display';
        break;
      case 'Specialty':
        $order = 'specialty_description';
        break;
      case 'Job Number':
        $order = 'job_number';
        break;
      case 'Job Type':
        $order = 'job_board_type';
        break;
      default:
        $order = 'job_number';
    }
  }
  else {
    $sort = 'ASC';
    $order = 'job_number';
  }

  // Query object
  $query = db_select("jobs", "j");  

  // Adding fields
  $query->fields('j');

  if(isset($_GET['location'])) {
    $query->condition('j.job_state_code', $_GET['location'], '='); 
  }

  // Set order by
  $query->orderBy($order, $sort);  

  // Pagination
  $query = $query->extend('TableSort')->extend('PagerDefault')->limit(20);

  // Executing query
  $result = $query->execute();

  // Looping for filling the table rows
  while($data = $result->fetchObject()) {
    $description = '<div class="thumbnail"><img src="/sites/all/themes/zen/vista_assets/images/job_headers/' . $data->job_image_file . '"/></div>';
    $description .= '<div class="title">' . $data->job_board_subtitle . '</div>';
    // Adding the rows
    $rows[] = array($description, $data->job_location_display, $data->specialty_description, $data->job_board_type, $data->job_number);    
  }

  $output .= theme('pager');

  // Setting the output of the field
  $output .= theme_table(
    array(
      'header' => $header,
      'rows' => $rows,
      'attributes' => array('id' => array('job-listing')),
      'sticky' => true,
      'caption' => '',
      'colgroups' => array(),
      'empty' => t("No records found.")
    )
  ).theme('pager');

  // Returning the output
  return $output;
}

这最终奏效了:

//get total records
$num_rows = $query->countQuery()->execute()->fetchField(); 

// add paging and sorting
$query = $query->extend('TableSort')->extend('PagerDefault')->limit(20);

//execute again
$result = $query->execute();

【问题讨论】:

    标签: mysql database api drupal drupal-7


    【解决方案1】:

    根据文档:https://api.drupal.org/api/drupal/includes!database!database.inc/function/db_query/7

    为了得到总行数最好使用db_query()函数,因为它有方法rowCount()返回查询总行数:

    <?php
    // Using the same query from above...
    $uid = 1;
    $result = db_query('SELECT n.nid, n.title, n.created
    FROM {node} n WHERE n.uid = :uid', array(':uid' => $uid));
    
    // Fetch next row as a stdClass object.
    $record = $result->fetchObject(); 
    
    // Fetch next row as an associative array.
    $record = $result->fetchAssoc();
    
    // Fetch data from specific column from next row
    // Defaults to first column if not specified as argument
    $data = $result->fetchColumn(1); // Grabs the title from the next row
    
    // Retrieve all records into an indexed array of stdClass objects.
    $result->fetchAll();
    
    // Retrieve all records as stdObjects into an associative array
    // keyed by the field in the result specified.
    // (in this example, the title of the node)
    $result->fetchAllAssoc('title');
    
    // Retrieve a 2-column result set as an associative array of field 1 => field 2.
    $result->fetchAllKeyed();
    // Also good to note that you can specify which two fields to use
    // by specifying the column numbers for each field
    $result->fetchAllKeyed(0,2); // would be nid => created
    $result->fetchAllKeyed(1,0); // would be title => nid
    
    // Retrieve a 1-column result set as one single array.
    $result->fetchCol();
    // Column number can be specified otherwise defaults to first column
    $result->fetchCol($db_column_number);
    
    // Count the number of rows
    $result->rowCount();
    ?>
    

    【讨论】:

    • 我不确定这对我有什么帮助,因为我的查询仍然有限制,所以如果我使用 rowcount(),它只会给我我的限制。听起来我仍然需要运行两个单独的查询。一个是获取行数,另一个是使用相同的标准,但要限制它,除非我遗漏了什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-30
    • 1970-01-01
    相关资源
    最近更新 更多