欧美大屁股bbbbxxxx,狼人大香伊蕉国产www亚洲,男ji大巴进入女人的视频小说,男人把ji大巴放进女人免费视频,免费情侣作爱视频

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

PHP編程

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

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

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

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

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

簡單的一句話總結(jié):一張表對(duì)應(yīng)兩張表。

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

1.1 文章表的結(jié)構(gòu)

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

1.2 視頻表結(jié)構(gòu)

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

1.3 評(píng)論表結(jié)構(gòu)

  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ū)別關(guān)聯(lián)于那張表的 我們這里它只有兩個(gè)值:App\Article 或 App\Video。

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

Article 和 Video:

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

Comment:

  public function video()
  {
    /**
     * 三個(gè)參數(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;
  }
});

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

希望本文所述對(duì)大家基于Laravel框架的PHP程序設(shè)計(jì)有所幫助。

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

如果侵犯了您的權(quán)利,請(qǐng)與我們聯(lián)系,我們將在24小時(shí)內(nèi)進(jìn)行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

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

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