Вы здесь

Проблема с join в hook_views_data

0

Добрый день, помогите пожалуйста разобраться.
Пытаюсь использовать hook_views_data для подключения сторонней таблицы в Views.

Для примера взял готовую базу данных : https://dev.mysql.com/doc/employee/en/sakila-structure.html
Хочу с помощью хука подключить таблицы employees (поля emp_no и first_name) и titles (поля emp_no и title)

На выходе хочу получить Views которая в одной колонке выведет First name во второй Title, т.е. с join-ить таблицы.
Хук стал делать по данному примеру: https://api.drupal.org/api/views/views.api.php/function/hook_views_data/...
Получилось сделать следующее:

<?php

function employees_views_data() {

  $data['employees']['table']['group'] = t('Employees table');
  $data['employees']['table']['base'] = array(
    'field' => 'emp_no',
    'title' => t('Employees table'),
    'help' => t('Employees table contains employees data.'),
    'database' => 'employees',
    'weight' => -10,
  );

  $data['employees']['table']['join'] = array(
    'titles' => array(
      'left_field' => 'emp_no',
      'field' => 'emp_no',
    ),
  );

  $data['employees']['emp_no'] = array(
    'title' => t('Employees content'),
    'help' => t('Some example employees.'),
    'relationship' => array(
      'base' => 'titles',
      'base field' => 'emp_no',
      'handler' => 'views_handler_relationship',
      'label' => t('Default label for the relationship'),
      'title' => t('Title shown when adding the relationship'),
      'help' => t('More information on this relationship'),
    ),
  );

  $data['employees']['first_name'] = array(
    'title' => t('First name'),
    'help' => t('First name.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );

  $data['titles']['title'] = array(
    'title' => t('Title'),
    'help' => t('Title.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );   

  return $data;
}

По умолчанию информацию из таблицы employees тянет, и всё отображает, но вот с join и relationship я запутался, вроде как во вьюхе появился на выбор relationship, но при его выборе нет нового поля Title.
Подскажите пожалуйста, где ошибка, первый раз с этим хуком работаю. Спасибо

Версия Drupal: 
7.x
Связанные проекты: 
Views
Вопрос задан 11.10.2018 - 19:35

Ответы

0

Опиши там же таблицу titles также, как описал таблицу employees, только без join-ов:

  $data['titles']['table']['group'] = t('Employees table');

  $data['titles']['table']['base'] = array(
     'field' => 'emp_no',
     'title' => t('Titles table'),
     'help' => t('Titles.'),
     'database' => 'employees',
     'weight' => -9,
 );

 $data['titles']['title'] = array(
   'title' => t('Title'),
   // и так далее
Ответ дан 17.10.2018 - 00:24

Ммм... то есть в этом же файле опишу ещё одну таблицу... а за счёт чего будет связь происходить, т.е. где описано что в таблице titles поле emp_no это внешний ключ к emp_no в таблице employees

Комментарий оставлен 17.10.2018 - 15:40
<?php

/**
 * Implements hook_cron_queue_info().
 */
function synch_employees_cron_queue_info() {
  $queue['synch_employees_queue'] = array(
    'worker callback' => 'synch_employees_item_process',
    'time' => 20,
  );
  return $queue;
}

/**
 * Implements hook_cron().
 */
function synch_employees_cron() {
  $queue = DrupalQueue::get('synch_employees_queue');
  watchdog("synch_employees","Users synchronization started. Remaining: " . $queue->numberOfItems());
  if ($queue->numberOfItems() == 0) {
    watchdog("synch_employees","Connect to external database and get all employees data");
    db_set_active('database');
    $sql = 'SELECT * FROM table';
    $result = db_query($sql);
    db_set_active();
    $item_employees_data = array();
    foreach ($result as $item_employees_data) {
      $queue->createItem($item_employees_data);
    }   
  }
}

/**
 * Synch users
 */
function synch_employees_item_process($data) {
  $query = new EntityFieldQuery();
  $result = $query
    ->entityCondition('entity_type', 'user')
    ->fieldCondition('field_user_personnel_number', 'value', $data->personnel_number)
    ->execute();
  if ($result) {    
    $uids = array_keys($result['user']);
    foreach ($uids as $uid) {
      update_user($uid,$data);
    }
    } else {
      create_user($data);
    }
}

/**
 * Create user
 */
function create_user($data) {
  user_save(NULL, array(
    'name' => $data->login,
    'mail' => $data->email,
    'init' => $data->email,
      'field_user_surname' => array(LANGUAGE_NONE => array(array('value' => $data->surname))),
      'field_user_name' => array(LANGUAGE_NONE => array(array('value' => $data->name))),
      'field_user_patronymic' => array(LANGUAGE_NONE => array(array('value' => $data->patronymic))),
      'field_user_personnel_number' => array(LANGUAGE_NONE => array(array('value' => $data->personnel_number))),
      'field_user_job_title' => array(LANGUAGE_NONE => array(array('value' => $data->job_title))),
      'field_user_number_department' => array(LANGUAGE_NONE => array(array('value' => $data->number_department))),
      'field_user_title_department' => array(LANGUAGE_NONE => array(array('value' => $data->title_department))),
      'field_user_number_subdepartment' => array(LANGUAGE_NONE => array(array('value' => $data->number_subdepartment))),
      'field_user_title_subdepartment' => array(LANGUAGE_NONE => array(array('value' => $data->title_subdepartment))),
      'field_user_phone' => array(LANGUAGE_NONE => array(array('value' => $data->phone))),
      'field_user_hash' => array(LANGUAGE_NONE => array(array('value' => $data->hash))),
    'status' => $data->employee_works,
    'roles' => array(DRUPAL_AUTHENTICATED_RID => TRUE),));
  watchdog("synch_employees","Created user: " . $data->personnel_number . " - " . $data->login . " - " . $data->surname . " " . $data->name . " " . $data->patronymic);
}

/**
 * Update user
 */
function update_user($uid,$data) {
  $user_fields = user_load($uid);
  if ($user_fields->field_user_hash and $user_fields->field_user_hash['und'][0]['value'] != $data->hash) {
    $user_fields->name = $data->login;
    $user_fields->mail = $data->email;
    $user_fields->init = $data->email;
    $user_fields->status = $data->employee_works;
      $user_fields->field_user_surname['und'][0]['value'] = $data->surname;
      $user_fields->field_user_name['und'][0]['value'] = $data->name;
      $user_fields->field_user_patronymic['und'][0]['value'] = $data->patronymic;
      $user_fields->field_user_job_title['und'][0]['value'] = $data->job_title;
      $user_fields->field_user_number_department['und'][0]['value'] = $data->number_department;
      $user_fields->field_user_title_department['und'][0]['value'] = $data->title_department;
      $user_fields->field_user_number_subdepartment['und'][0]['value'] = $data->number_subdepartment;
      $user_fields->field_user_title_subdepartment['und'][0]['value'] = $data->title_subdepartment;
      $user_fields->field_user_phone['und'][0]['value'] = $data->phone;
      $user_fields->field_user_hash['und'][0]['value'] = $data->hash;      
    user_save($user_fields);
  watchdog("synch_employees","Updated user: " . $user_fields->field_user_personnel_number['und'][0]['value'] . " - " . $user_fields->name . " - " . $user_fields->field_user_surname['und'][0]['value'] . " " . $user_fields->field_user_name['und'][0]['value'] . " " . $user_fields->field_user_patronymic['und'][0]['value']); 
  }
}
Комментарий оставлен 04.04.2019 - 16:12