如果内容作者与登录用户具有相同的实体引用值,则在视图中显示内容

问题描述

标题几乎解释了它。我有一个名为“公司”的用户实体引用字段(节点)。我想在一个视图中显示所有内容,其中该内容的作者与登录用户具有相同的“公司”值。我对实现这一目标的关系有点困惑。

好的,我能够根据 Kien 的回答完成这项工作。如果使用实体参考 7-x.1.5 而不是 'field_company_nid',则正确的列名称是 'field_company_target_id'

/**
 * Implements hook_views_query_alter().
 */
function your_module_views_query_alter(&$view,&$query) {
  if ($view->name == 'article' && $view->current_display == 'page') { // replace 'article' and 'page' by your view's machine name and display's machine name
    $author_join = new views_join();
    $author_join->table = 'field_data_field_company'; // 'field_company' is machine name of the user's field referencing to Company
    $author_join->field = 'entity_id';
    $author_join->left_table = 'node';
    $author_join->left_field = 'uid';
    $author_join->type = 'left';
    $view->query->add_relationship('author_company',$author_join,'node');

    $current_join = new views_join();
    $current_join->table = 'field_data_field_company'; // 'field_company' is machine name of the user's field referencing to Company
    $current_join->field = 'field_company_target_id';
    $current_join->left_table = 'author_company';
    $current_join->left_field = 'field_company_target_id';
    $current_join->type = 'left';
    $view->query->add_relationship('current_company',$current_join,'author_company');

    global $user;
    $view->query->where[1]['conditions'][] = array(
      'field' => 'current_company.entity_id','value' => $user->uid,'operator' => '='
    );
  }
}

解决方法

通过简单地设置视图,您想要的似乎有点困难。您可能需要一些自定义代码来更改视图查询。以下是使用 hook_views_query_alter() 的方法:

  1. 创建一个自定义模块(假设它是your_module
  2. 在文件 your_module.module 中,实现 hook_views_query_alter()
/**
 * Implements hook_views_query_alter().
 */
function your_module_views_query_alter(&$view,&$query) {
  if ($view->name == 'article' && $view->current_display == 'page') { // replace 'article' and 'page' by your view's machine name and display's machine name
    $author_join = new views_join();
    $author_join->table = 'field_data_field_company'; // 'field_company' is machine name of the user's field referencing to Company
    $author_join->field = 'entity_id';
    $author_join->left_table = 'node';
    $author_join->left_field = 'uid';
    $author_join->type = 'left';
    $view->query->add_relationship('author_company',$author_join,'node');

    $current_join = new views_join();
    $current_join->table = 'field_data_field_company'; // 'field_company' is machine name of the user's field referencing to Company
    $current_join->field = 'field_company_nid';
    $current_join->left_table = 'author_company';
    $current_join->left_field = 'field_company_nid';
    $current_join->type = 'left';
    $view->query->add_relationship('current_company',$current_join,'author_company');

    global $user;
    $view->query->where[1]['conditions'][] = array(
      'field' => 'current_company.entity_id','value' => $user->uid,'operator' => '='
    );
  }
}
  1. 启用您刚刚创建的模块。