Implementing single table inheritance

Relational databases do not support inheritance. If we need to store inheritance in the database, we should somehow support it through code. This code should be efficient, so that it should generate as few JOINs as possible. A common solution to this problem was described by Martin Fowler and is named single table inheritance.

When we use this pattern, we store all the class tree data in a single table and use the type field to determine a model for each row.

As an example, we will implement the single table inheritance for the following class tree:


|- SportCar

|- FamilyCar

Getting ready

  1. Create a new application using the Composer package manager, as described in the official guide at ...

Get Yii2 Application Development Cookbook - Third Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.