Implementing Single Table Inheritance in Laravel Using Eloquent
Scenario:
You have a model named Post and want to divide posts into two types: articles and questions, using inheritance.
Single Table Inheritance
Single table inheritance involves maintaining all types in the same table, with a column to distinguish between them. While this approach can be simpler, it can result in a lot of NULL values due to columns that are not applicable to all types.
Multi Table Inheritance
Multi table inheritance is a cleaner approach that splits the data into multiple tables. A postable column indicates the type of post, and a postable_id references the primary key in the corresponding table.
Implementing Multi Table Inheritance in Eloquent
Post Model:
Add a postable relationship to the Post model, which will be a polymorphic relationship:
<code class="php">class Post extends Eloquent { public function postable() { return $this->morphTo(); } }</code>
Question and Article Models:
Create separate models for each post type and establish the relationship with the Post model:
<code class="php">class Question extends Post { public function post() { return $this->morphOne('Post', 'postable'); } }</code>
<code class="php">class Article extends Post { public function post() { return $this->morphOne('Post', 'postable'); } }</code>
Usage:
Create a new question:
Recommendation:
For a more user-friendly implementation, it is recommended to consolidate the model creation logic into reusable functions within each model class.
The above is the detailed content of How to Implement Multi-Table Inheritance for Posts in Laravel Using Eloquent?. For more information, please follow other related articles on the PHP Chinese website!