drupal - 在 views_query_alter() 中向 View 查询添加表连接、位置和排序依据

标签 drupal drupal-7 drupal-views

我正在尝试修改 Drupal 中的 View 查询( View 版本 3,Drupal 版本 7)。

我想要做的是在运行之前更改查询,以便它 LEFT JOINs 一个表,在该表中我为节点分配了权重。

如果我要在 SQL 中编写我想要的查询,它将如下所示:

    SELECT a.nid, a.title, a.description
    FROM node a
    LEFT OUTER JOIN node_weights b
    ON a.nid = b.nid
    WHERE b.uid = $uid
    ORDER BY b.weight DESC

当我在查询分析器中运行它时,这个查询就像一个冠军。所以,现在我需要让它在我的模块中工作。

我已经在各种博客上看到了多种方法,详细介绍了修改 View 查询的不同方法,但它们似乎针对的是不同版本的 View。因此,尝试确定我正在查看的任何内容是否可能适用于我的应用程序是非常令人困惑的。

看来我需要使用一个 MODULE_NAME_views_tables() 函数来告诉 Views 我要加入的表和节点表之间的关系是什么。

我在 MODULE_NAME.views.inc 中添加了以下函数:
    function MODULE_NAME_views_tables() {
      $tables['node_weights'] = array(
        "name" => "node_weights",
        "join" => array(
          "left" => array(
            "table" => "node",
            "field" => "nid"
          ),
          "right" => array(
            "field" => "nid"
          ),
        ),
      );
      return $table;  
    }

这似乎确实有效,因为当我使用 Krumo 查看查询数组时,我在“table_queue”元素中看到了我的“node_weights”表。

在 views_query_alter() 函数中,我希望它像这样工作:
    function MODULE_NAME_views_query_alter(&$view, &$query) {
      $uid = $_COOKIE['uid']; 
      $view->query->add_relationship('node_weights', new views_join('node_weights', 'nid', 'node', 'nid','LEFT'));
      $view->query->add_where('node_weights', "node_weights.uid", $uid);
      krumo($query);
    }

这个函数非常糟糕。虽然我的连接表出现在 $view 对象中,但 add_relationship 方法对第三个参数抛出错误,但我没有看到任何在线示例有 3 个参数,所以我不知道它缺少什么。

另外,我很确定我的 add_where 方法不正确,但我不知道输入实际上应该是什么。这只是一个盲目的猜测。

底线是我想将节点表加入到我的 node_weights 表中,然后确保在查询中使用我的权重以降序对结果进行排序,其中用户 id = 我表中的用户 id,并且表在 nid 字段上连接。

提前致谢。

最佳答案

加入 JOIN 后,WHERE 很容易添加。您可以在查询中进行更改(Drupal 7)。

function MODULE_NAME_views_query_alter(&$view, &$query){

// Only alter the view you mean to.
if($view->name == 'VIEW NAME' && $view->current_display == 'DISPLAY'){

    // Create the join.
    $join = new views_join();
    $join->table = 'table_name';
    $join->field = 'entity_id';
    $join->left_table = 'node';
    $join->left_field = 'nid';
    $join->type = 'left';
    // Add the join the the view query.
    $view->query->add_relationship('table_name', $join, 'node');

    // Add the where.
    $view->query->where[1]['conditions'][] = array(
        'field' => 'table_name.collumn_name',
        'value' => 'value',
        'operator' => '='
    );
}}

关于drupal - 在 views_query_alter() 中向 View 查询添加表连接、位置和排序依据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6851945/

相关文章:

drupal - 按类别对内容进行分组 - Drupal

Drupal 返回 View 中的结果数

Drupal 7 次浏览 : Combine exposed filter with contextual filter?

php - Drupal 自定义节点表单

jQuery - Ajax 选择选项 Drupal 自定义表单 'POST Error 500'

performance - 如何正确设置 Drupal 7 中的 View 字段主题

drupal - 如何为 Drupal 创建 RSS 源?

drupal - 为选择列表显示标签给定键

forms - Drupal 7 - 覆盖基本表单 HTML 标记

php - 多次调用通配符加载器函数 (_load)