首頁  >  文章  >  資料庫  >  如何使用 Laravel 的 Eloquent(從 Post 模型擴展)實作 Article 和 Question 模型的單表繼承?

如何使用 Laravel 的 Eloquent(從 Post 模型擴展)實作 Article 和 Question 模型的單表繼承?

Barbara Streisand
Barbara Streisand原創
2024-10-25 05:08:02505瀏覽

How can you implement single table inheritance for Article and Question models using Laravel's Eloquent, extending from the Post model?

使用Laravel 的Eloquent 實現單表繼承

問題:

給定Post 模型:

<code class="php">class Post extends Eloquent {

    // Model code...
}</code>

如何實現Article 和Question 模型的繼承,允許它們從Post 擴展?

單表繼承

單表繼承涉及儲存所有模型資料在具有類型列的單一表中以區分型號。但是,由於特定模型類型未使用列,這種方法可能會導致大量 NULL 值。

多表繼承

多表繼承採用多態性,利用單獨的表來實現每個模型,同時透過參考表將它們連接起來。參考表包括 postable_id 和 postable_type 等欄位。

Eloquent 模型設定

在Post 模型中,定義morphTo 關係:

<code class="php">public function postable(){
    return $this->morphTo();
}</code>

在問題模型中(與文章類似):

<code class="php">public function post(){
    return $this->morphOne('Post', 'postable');
}</code>

用法:

  • 擷取所有貼文:Post::all()
  • 擷取所有問題: Question::all( )
  • 從帖子中獲取問題詳細資訊:$question_column2 = $post->postable->question_column2
  • 檢查帖子類型:if( $post->postable instanceof 問題)
  • 建立一個新問題:
<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>

結論

多表繼承提供了與單表繼承相比,更有效率的資料庫結構。它需要額外的模型邏輯,但它提供了一種更靈活和可擴展的方法來處理 Laravel 的 Eloquent 中的模型繼承。

以上是如何使用 Laravel 的 Eloquent(從 Post 模型擴展)實作 Article 和 Question 模型的單表繼承?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn