Creating tables relations in Views programmatically

Public

Imagine that you have a custom table with some fields of your custom module and need to create a relation with a core table, e.g. users.

This snippet show how you can accomplish it in Views using the hook_views_data_alter() in a simple way.

How to use:
- Put the snippet below inside a custom.module file
- Change the dummy values on the snippet

Tip: if you have more than one relation (two or more fields related), change the line $data['the_name_of_your_custom_table']['the_name_of_your_custom_table'] = array( to something like $data['the_name_of_your_custom_table']['the_name_of_your_custom_table_related_something'] = array( for each relation.

Don't forget, you need more lines of code to create your custom entity.

Happy Drupal.

</> CopyGet raw version
php
  1. /**
  2.  * Implements hook_views_data_alter()
  3.  */
  4. function you_module_views_data_alter(&$data) {
  5. $data['the_name_of_your_custom_table']['the_name_of_your_custom_table'] = array(
  6. 'title' => t('This is what you see on Relationships Views area'),
  7. 'help' => t('A sentence to help the user explain what is this.'),
  8. // here where the magic begins
  9. 'relationship' => array(
  10. 'base' => 'users', // the core table that you join in.
  11. 'base field' => 'uid', // the field name of the core table that make the relation.
  12. 'field' => 'my_custom_id', // the field name of YOUR table related with the core table.
  13. 'handler' => 'views_handler_relationship', // default
  14. 'label' => t('UID vs my custom table.'), // Some text showed on the Views Fields area.
  15. ),
  16. );
  17. }