Multi Table Inheritance in Laravel's Eloquent
Implementing single table inheritance might sound like a convenient solution for extending models, but it comes with drawbacks like increased database size due to numerous NULL values and complexities when querying for specific columns. Instead, multi table inheritance offers a cleaner approach.
Schema Design
Create separate tables for shared columns and unique columns for each model type. For instance:
Eloquent Models
Define the Post model as the parent class.
<code class="php">class Post extends Eloquent { // Shared column, relationships, etc. public function postable(){ return $this->morphTo(); } }</code>
Create child models like Question for each postable type.
<code class="php">class Question extends Post { public function post(){ return $this->morphOne('Post', 'postable'); } }</code>
Usage
Creating New Models
Involves creating records in both the shared table (posts) and type-specific table (questions).
<code class="php">$question = new Question(); // Create a question record $question->question_column = 'test'; $question->save(); $post = new Post(); // Create a post record $post->shared_column = 'New Question Post'; $post->save(); // Link them together $question->post()->save($post);</code>
This approach ensures a more efficient database structure and provides a scalable solution for model inheritance in Laravel.
The above is the detailed content of ## Multi-Table Inheritance in Laravel\'s Eloquent: A Cleaner Approach?. For more information, please follow other related articles on the PHP Chinese website!