There are times where you will need to define a relation on your own with custom code. Typically, when working with custom data in Drupal, you would more than likely create a new entity type; this topic is covered in Chapter 9, Configuration Management - Deploying in Drupal 8. This is not always the case, however, and you may just need a simple method of storing data. An example can be found in the Database Logging module. The Database Logging module defines a schema for a database table and then uses hook_views_data to expose its database table to Views.
The dblog_schema hook implementation returns a uid column on the watchdog database table created by the module. That column is then exposed to Views using the following definition:
$data['watchdog']['uid'] = array(
'title' => t('UID'),
'help' => t('The user ID of the user on which the log entry
was written..'),
'field' => array(
'id' => 'numeric',
),
'filter' => array(
'id' => 'numeric',
),
'argument' => array(
'id' => 'numeric',
),
'relationship' => array(
'title' => t('User'),
'help' => t('The user on which the log entry as written.'),
'base' => 'users',
'base field' => 'uid',
'id' => 'standard',
),
);
This array tells Views that the watchdog table has a column named uid. It is numeric in nature for its display, filtering capabilities, and sorting capabilities. The relationship
key is an array of information that instructs Views how to use this to provide a relationship (LEFT JOIN) on the users table. The User entity uses the users table and has the primary key of uid.