Difference between creating a relationship and adding a join

We encourage users to post events happening in the community to the community events group on https://www.drupal.org.
wodenx's picture

Hello All,

Just getting started with the views API and trying to find my way. Here's my scenario.

I am developing a module which will serve as a bridge between two other modules (let's call them A and B). Neither module knows about the other, but both expose their tables to Views, and there is a field in A's table that relates to a field in B's table (unbeknownst to either).

Basically, I want to make the fields from B available in views based on (or including) A. From what I can tell there are two ways to do this (assuming that table_a_field relates to table_b_field):

(1) Create a new join for module B - as:

  $data['table_b']['table']['join']['table_a'] = array(
    'left_field' => 'table_a_field',
    'field' => 'table_b_field'
  );

or, (2) Create a new relationship for the field in module A - as:

  $data['table_a']['table_b_relationship'] = array(
    'group' => t('My Group'),
    'title' => t('B'),
    'help' => t('Create a relationship to B's data'),
    'relationship' => array(
      'handler' => 'views_handler_relationship',
      'base' => 'table_b',
      'base field' => 'table_b_field',
      'relationship field' => 'table_a_field',
      'label' => t('B Stuff'),
    ),
  );

First of all - am I right that either of these methods will work? Second - what are the relative merits of one over the other (aside from the fact that method (2) requires the person creating the view to explicitly include the relationship). Third - can the above code go in my hook_views_data(), or does it have to go into hook_views_data_alter()?

Thanks so much in advance for any insights.

Comments

You use option 1) if that is

merlinofchaos's picture

You use option 1) if that is the only way that your table will be joined in, or at least is like a 90-95% case. You use option 2 if there are multiple ways that the table might be joined in. You can use BOTH options, where 1) is always available for the 'most often' case, and then option 2) for the tweaky/more powerful case.

The rule on hook_views_data vs hook_views_data_alter is:

If your module owns (defines) the table, use hook_views_data. If another module owns the table, then use hook_views_data_alter because you're adding fields to another module's table.

Thanks - exactly the info i

wodenx's picture

Thanks - exactly the info i was looking for

Views Developers

Group organizers

Group notifications

This group offers an RSS feed. Or subscribe to these personalized, sitewide feeds:

Hot content this week