The data about the teams our players belong to is stored in a different table. This means that, at a database level, a join will have to be created to pull them together. In Views lingo this is a relationship in the sense that one table relates to another and the way these are declared is directional from a field to another from the joined table. So, let's see how we can define the team_id field from the players table to join with the teams table on its id field:
$data['players']['team_id'] = array( 'title' => t('Team ID'), 'help' => t('The unique team ID of the player.'), 'field' => array( 'id' => 'numeric', ), 'relationship' => array( 'base' => 'teams', 'base field' => 'id', 'id' => 'standard', 'label' => t('Player team'), ), );
First of all, we define it to Views as a field. Then, because we also might want to display the team ID, we can define it as a field as well using the numeric plugin, the same way we defined the ID of the player records themselves. But here comes another responsibility of this field in the form of a relationship, which requires four pieces of information:
- base: The name of the table we are joining
- base field: The name of the field on the table we are joining that will be used to join
- id: The ViewsRelationship plugin ID to use for the relationship
- label: How this relationship will be labeled in the UI
Usually, the standard relationship plugin will suffice, but we can always create one ourselves if we need to. It's doubtful you will ever need to though.
This definition now allows us to add a relationship to the teams table in Views. However, even if the database engine joins the two tables, we haven't achieved anything as we also want to output some fields from the new table. So for that, we first have to define the table itself, as we did for the players:
// Teams table $data['teams'] = []; $data['teams']['table']['group'] = t('Sports');
Note that it is not mandatory to define it as a base table if we don't want to create Views that are basing themselves on this table. In our case, it can be secondary to player information. Then, just as we did before, we can define a couple of team fields:
// Teams fields $data['teams']['name'] = array( 'title' => t('Name'), 'help' => t('The name of the team.'), 'field' => array( 'id' => 'standard', ), ); $data['teams']['description'] = array( 'title' => t('Description'), 'help' => t('The description of the team.'), 'field' => array( 'id' => 'standard', ), );
There is nothing new here, just the basic data output for our two columns. But now, we can go to the View in the UI, add a relationship to the teams table and then include the name and description of the teams our players belong to. Neat.