If you want to add custom views relationship to another entity or custom table then in Drupal we can do this with views_data handler. In the Drupal entity annotation we add different type of handlers for different purposes. The views_data handler is for views to add custom fields, relationships, arguments, filters etc.
/**
* Defines the Event entity.
*
* @ingroup base_event
*
* @ContentEntityType(
* id = "event",
* label = @Translation("Event"),
* handlers = {
* "storage" = "Drupal\base_event\EventStorage",
* "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
* "list_builder" = "Drupal\base_event\EventListBuilder",
* "views_data" = "Drupal\base_event\Entity\EventViewsData",
* "translation" = "Drupal\base_event\EventTranslationHandler",
*
* "form" = {
* "default" = "Drupal\base_event\Form\EventForm",
* "add" = "Drupal\base_event\Form\EventForm",
* "edit" = "Drupal\base_event\Form\EventForm",
* "delete" = "Drupal\base_event\Form\EventDeleteForm",
* },
* "route_provider" = {
* "html" = "Drupal\base_event\EventHtmlRouteProvider",
* },
* "access" = "Drupal\base_event\EventAccessControlHandler",
* },
* )
*/
In the views_data we create a new relationship to the another entity with has the event_id but event content does has the relations to that entity.
<?php
namespace Drupal\base_event\Entity;
use Drupal\views\EntityViewsData;
/**
* Provides Views data for Event entities.
*/
class EventViewsData extends EntityViewsData {
/**
* {@inheritdoc}
*/
public function getViewsData() {
$data = parent::getViewsData();
// Ticket fields.
$this->attachEventTickets($data);
return $data;
}
/**
* Create the relation between event to tickets.
*
* @param $data
*
* @return void
*/
protected function attachEventTickets(&$data) {
foreach ($data as $table_name => $table_data) {
$data[$table_name]['unique_name'] = [
'title' => t('Ticket content'),
'help' => t('Relate ticket content to the event content'),
'relationship' => [
// Views name of the table to join to for the relationship.
'base' => 'ticket',
// Database field name in the other table to join on.
'base field' => 'event_id',
// ID of relationship handler plugin to use.
'id' => 'standard',
// Default label for relationship in the UI.
'label' => t('Event\'s Ticket'),
// Table column name.
'field' => 'id'
],
];
}
}
}