Polymorphic ActiveRecord models

I have Lesson and PrivateLesson models that corresponds to lesson & private_lesson tables. I have generic fields common to all lesson types in lesson table and private lesson specific fields in private_lesson table.

When creating a new private lesson, currently I’m going this.

$lesson = new Lesson();

if($lesson->save()) {

$privateLesson = new PrivateLesson();


Instead, is it possible to simply instantiate Lesson model, get it automatically instantiate necessary models based on the field given and populate child tables?

I don’t really know if this is what you are asking but maybe link() or call it in the aftersave()?

Yes, I could do that, but I’m looking for more object oriented way. Kind of single table / class table inheritance or polymorphic association. Consumer of the class shouldn’t know what class he has to instantiate, but simply instantiate the generic class which should do the magic.

I’m not exactly sure what how you expect it to work but perhaps you may get some inspiration here: https://github.com/samdark/yii2-cookbook/blob/master/book/ar-single-table-inheritance.md