ActiveReocrd and table inheritance

Hi, can anybody tell how to store in database such a set of AR-classes:

  • Person

    • Employee extended from Person

      • ProjectManager extended from Employee

      • Engineer extended from Employee

I would like to have something like this

class Person extends CActiveRecord {



class Employee extends Person {



class ProjectManager extends Employee {



class Engineer extends Employee {



// example 1

$engineer = Engineer::model()->findByPk(1);

$engineer->name = 'Steve';

// example 2

if (isset($_POST['Engineer'])) {

    $engineer = new Engineer();

    // $_POST['Engineer'] may contain 'name' property inherited from Person class

    $engineer->attributes = $_POST['Engineer'];



I cannot figure out any way to implement this with Yii ActiveRecord, any thoughts?

  • storing data for all classes in one table looks clumsy (especially in real application with wider hierarhy)

  • I know that I can access name property like this $engineer->person->name using BELONGS_TO relation, but $engineer->name and inheritance looks better

Thank you

I believe the best way is NOT to extend from class to class, but rather to have a model class for each of your tables.

After this step, define your relations between your tables within the models(or let gii do this for you).

Having 4 tables and the correct relations between, then is very easy to play with, and pull data from .

For example, TBL1 might depend ON TBL2 which depends on TBL3,

then you you query the tables, using the with() option from AR and you will end up with something like:

TBL1data->TBL2data->TBL3data;(purely as example, as each of the tables might return a subset of records, but you get the point)

Hope it helps.

Thanks for your reply, I know this way, but accessing of object’s property is too often procedure to write something like this:


I would like to write $engeener->name instead, but I have no idea how to reach such a behavior

It’s called single table inheritance. Here is the implementation (description is in Russian):

Thank you, good examples

STI with Yii is really simple, but this is not what i’m looking for

Hey guys,

Was looking to do a similar thing. Thought about views, Single Table Inheritance and the like, but was worried about scalability and efficiency. I found this post which might be helpful, describing Class Table Inheritance as a database design. I haven’t implemented it yet, so I can’t say how well it works, but worth looking into.

Hope it helps!