27 June 2023

In Drupal 7, you can use the hook_views_data hook to define custom tables and relationships for Views. When implementing relationships, you need to define the relationship key in your hook_views_data implementation. By implementing the relationship in hook_views_data, you allow Views to utilize this relationship when building queries. Once the relationship is defined, you can select and configure it when adding or editing a relationship in the Views UI.

Source code viewer
  1. /**
  2.  * Implements hook_views_data().
  3.  */
  4. function HOOK_views_data() {
  5. $data = array();
  6.  
  7. // Define your base table.
  8. $data['MY_TABLE']['table'] = array(
  9. 'group' => t('My Table'),
  10. 'base' => array(
  11. 'field' => 'PRIMARY_KEY',
  12. 'title' => t('My Table'),
  13. 'help' => t('My table description.'),
  14. ),
  15. );
  16.  
  17. // Define the relationship.
  18. $data['MY_TABLE']['my_relationship'] = array(
  19. 'title' => t('My Relationship'),
  20. 'help' => t('Help text for my relationship.'),
  21. 'relationship' => array(
  22. 'base' => 'my_related_table',
  23. 'base field' => 'related_table_id',
  24. 'field' => 'my_table_id',
  25. 'handler' => 'views_handler_relationship',
  26. 'label' => t('My Relationship Label'),
  27. ),
  28. );
  29.  
  30. // ...
  31.  
  32. return $data;
  33. }
  34.  
  35. // Remember to clear the Drupal cache after implementing or modifying hook_views_data to ensure that the changes take effect.
  36.  
Programming Language: PHP