drupal的高级数据库查询

见到一篇不错的文章 贴出来大家分享一下
参考taxonomy模块中查询术语节点的部分,其实可以写得更简单,不知道老外是故意写得很晦涩还是。。。。

 
if (count($tids) > 0) {
    $joins = ”;
    $wheres = ”;
    $args = array();
    foreach ($tids as $index => $tid) {
      $joins .= ‘ INNER JOIN {term_node} tn’. $index .’ USING(nid)’;
      $placeholders = implode(’,', array_fill(0, count($tids), ‘%d’));
      $wheres .= ‘ AND tn’. $index .’.tid IN (’. $placeholders .’)';
      $args = array_merge($args, $tids);
    }
    $sql = ‘SELECT DISTINCT(n.nid), n.sticky, n.title, n.created FROM {node} n ‘. $joins .’ WHERE n.status = 1 ‘. $wheres;
    $result = db_query(db_rewrite_sql($sql), $args);
// 之前这里写成了 db_query(db_rewrite_sql($sql, $args)); 好久才发现问题,汗一个。
    while ($product = db_fetch_object($result)) {
      // 如果用户已经在改产品发布了该驱动或者说明书,跳过不进行筛选。
      if ($product->nid == $form_values['pid']) {
        continue;
      }
      $rows[$product->nid] = check_plain($product->title);
    }
    variable_set(’product_filter’, $rows);
  }