Home  >  Article  >  Database  >  ## Multi-Table Inheritance in Laravel\'s Eloquent: A Cleaner Approach?

## Multi-Table Inheritance in Laravel\'s Eloquent: A Cleaner Approach?

Barbara Streisand
Barbara StreisandOriginal
2024-10-27 01:59:30516browse

## Multi-Table Inheritance in Laravel's Eloquent: A Cleaner Approach?

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:

  • posts (shared_column)
  • questions (question_column, question_column2)
  • articles (article_column, article_column2)

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

  • Retrieve all posts: $posts = Post::all();
  • Retrieve all questions: $questions = Question::all();
  • Get question columns from a post: $question_column2 = $post->postable->question_column2;
  • Check which type a post is: echo 'type: '.get_class($post->postable);

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn