Question:
Given the Post model:
<code class="php">class Post extends Eloquent { // Model code... }</code>
How can you implement inheritance for Article and Question models, allowing them to extend from Post?
Single Table Inheritance
Single table inheritance involves storing all model data in a single table with a type column to differentiate models. However, this approach can lead to numerous NULL values due to unused columns for specific model types.
Multi Table Inheritance
Multi table inheritance employs polymorphism, utilizing separate tables for each model while connecting them through a reference table. The reference table includes columns like postable_id and postable_type.
Eloquent Model Setup
In the Post model, define a morphTo relationship:
<code class="php">public function postable(){ return $this->morphTo(); }</code>
In the Question model (similar for Article):
<code class="php">public function post(){ return $this->morphOne('Post', 'postable'); }</code>
Usage:
<code class="php">$post = new Post(); $post->shared_column = 'New Question Post'; $post->save(); $question = new Question(); $question->question_column = 'test'; $question->post()->save($post);</code>
Conclusion
Multi table inheritance offers a more efficient database structure compared to single table inheritance. It requires additional model logic, but it provides a more flexible and scalable approach for handling model inheritance in Laravel's Eloquent.
The above is the detailed content of How can you implement single table inheritance for Article and Question models using Laravel\'s Eloquent, extending from the Post model?. For more information, please follow other related articles on the PHP Chinese website!