Module Development

Add Relationships Between 2 Tables in Views for Drupal 8, 9, and 10

In Expose a Custom Database Table to Views we learned how to let Views know about custom tables created by a Drupal module. In that example, the custom table was a stand-alone one, without any connections to the other tables in the database. However, it's common for data in one table to relate to data in another.

For example, you might have TableA with the columns first_name, last_name, email and TableB with the columns email, score. TableA.email and TableB.email can be used to join the two tables together.

It's useful to define these relationships for Views so that when TableA is used as the base table the fields from TableB are also available in the view. When the fields from a related table are automatically loaded, this is known as an implicit relationship. Our earlier example could benefit from the relationship with the users_field_data. This relationship will allow us to associate First Name and Last Name fields from the subscriptions table with the users on the site.

In this tutorial we'll:

  • Define the difference between implicit and explicit relationships in Views.
  • Learn how to create an implicit relationship between 2 tables using hook_views_data.

By the end of this tutorial you should know how to describe custom implicit relationships in a view, making data from one or more secondary tables available to the Views query builder.