雷火电竞-中国电竞赛事及体育赛事平台

歡迎來到入門教程網(wǎng)!

PHP編程

當前位置:主頁 > 網(wǎng)絡編程 > PHP編程 >

Laravel5.1 框架模型多態(tài)關聯(lián)用法實例分析

來源:本站原創(chuàng)|時間:2020-01-11|欄目:PHP編程|點擊:

本文實例講述了Laravel5.1 框架模型多態(tài)關聯(lián)用法。分享給大家供大家參考,具體如下:

什么是多態(tài)關聯(lián)? 一個例子你就明白了:好比如說評論 它可以屬于視頻類 也可以屬于文章類,當有個需求是 從評論表中取到視頻類的數(shù)據(jù),這就需要用到多態(tài)關聯(lián)了。

簡單的一句話總結:一張表對應兩張表。

1 實現(xiàn)多態(tài)關聯(lián)

1.1 文章表的結構

  public function up()
  {
    Schema::create('articles', function (Blueprint $table) {
      $table->increments('id');
      $table->string('title');
      $table->text('body');$table->timestamps();
    });
  }

1.2 視頻表結構

  public function up()
  {
    Schema::create('videos', function (Blueprint $table) {
      $table->increments('id');
      $table->string('title');
      $table->text('description');
      $table->timestamps();
    });
  }

1.3 評論表結構

  public function up()
  {
    Schema::create('comments', function (Blueprint $table) {
      $table->increments('id');
      $table->text('content');
      $table->integer('item_id');
      $table->string('item_type');
      $table->timestamps();
    });
  }

↑ 這里需要指定 item_id 和 item_type 單一介紹一下 item_type 它主要是區(qū)別關聯(lián)于那張表的 我們這里它只有兩個值:App\Article 或 App\Video。

1.4 編寫多態(tài)關聯(lián)

Article 和 Video:

  public function comments()
  {
    /**
     * 第二個參數(shù):如果你的前綴是item_ 那么就寫item 如果是別的就寫別的。
     * 第三個參數(shù):item_type
     * 第四個參數(shù):item_id
     * 第五個參數(shù):關聯(lián)到那個表的鍵
     * (以上除了第二個參數(shù)都可以省略)
     */
    return $this->morphMany(Comment::class, 'item', 'item_type', 'item_id', 'id');
  }

Comment:

  public function video()
  {
    /**
     * 三個參數(shù)都可以省略 不過K建議你還是寫全
     */
    return $this->morphTo('item', 'item_type', 'item_id');
  }

使用:

Route::get('/', function () {
  $video = App\Video::find(8);
  foreach ($video->comments as $comment) {
    echo $comment->id . ": " . $comment->item_type;
  }
});

更多關于Laravel相關內(nèi)容感興趣的讀者可查看本站專題:《Laravel框架入門與進階教程》、《php優(yōu)秀開發(fā)框架總結》、《php面向?qū)ο蟪绦蛟O計入門教程》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》

希望本文所述對大家基于Laravel框架的PHP程序設計有所幫助。

上一篇:PHP變量作用域(全局變量&局部變量)&global&static關鍵字

欄    目:PHP編程

下一篇:php 實現(xiàn)svg轉(zhuǎn)化png格式的方法分析

本文標題:Laravel5.1 框架模型多態(tài)關聯(lián)用法實例分析

本文地址:http://www.jygsgssxh.com/a1/PHPbiancheng/10965.html

網(wǎng)頁制作CMS教程網(wǎng)絡編程軟件編程腳本語言數(shù)據(jù)庫服務器

如果侵犯了您的權利,請與我們聯(lián)系,我們將在24小時內(nèi)進行處理、任何非本站因素導致的法律后果,本站均不負任何責任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權所有