Donnie
Donnie

Reputation: 6351

Model inheritance in Laravel 4

Groundwork

I have a database design (snipped to relevant portions) like so:

records
  entities
    people

where no proper relationship exists between the tables, but rather records is extended by entities is extended by people by sharing the same id.

I have my Eloquent models similarly defined so that Record is extended by Entity is extended by Person.

Goal

Record and Entity are abstract and I want to simply use Person and other models at that level in the hierarchy.

Problem

How do I 'link' Record and Entity to Person to make this all work seamlessly? I don't think relationships is appropriate. I assume it's related to something like this:

protected __construct() {
  parent::__construct();
}

Upvotes: 1

Views: 1454

Answers (1)

hayhorse
hayhorse

Reputation: 2652

I suggest you still create a model for Person, Entity, and Record, and link them together with "belongsTo" relationships. (add entity_id column to "People" table, add "record_id" to "Entities" table).

If you are only working with the Person model, you could add a "saved" model observer to create the entity and record entries whenever you create a Person, and tie them all together with a global id.

http://laravel.com/docs/eloquent#model-observers

If you did it this way, you could access the person's entity and record field by doing something like:

$person->entity->fieldName

$person->record->fieldName

All that being said, this seems way too complicated. I would only have one table for People and store all the person's data there. imo.

Upvotes: 1

Related Questions