当前位置:首页 > CMS教程 > 其它CMS > 列表

Laravel5.1 框架模型多态关联用法实例分析

发布:smiling 来源: PHP粉丝网  添加日期:2022-02-04 13:51:31 浏览: 评论:0 

本文实例讲述了Laravel5.1 框架模型多态关联用法,分享给大家供大家参考,具体如下:

什么是多态关联? 一个例子你就明白了:好比如说评论 它可以属于视频类 也可以属于文章类,当有个需求是 从评论表中取到视频类的数据,这就需要用到多态关联了。

简单的一句话总结:一张表对应两张表。

1 实现多态关联

1.1 文章表的结构

  1. public function up() 
  2. { 
  3.   Schema::create('articles', function (Blueprint $table) { 
  4.     $table->increments('id'); 
  5.     $table->string('title'); 
  6.     $table->text('body');$table->timestamps(); 
  7.   }); 
  8. } 

1.2 视频表结构

  1. public function up() 
  2. { 
  3.   Schema::create('videos', function (Blueprint $table) { 
  4.     $table->increments('id'); 
  5.     $table->string('title'); 
  6.     $table->text('description'); 
  7.     $table->timestamps(); 
  8.   }); 
  9. } 

1.3 评论表结构

  1. public function up() 
  2. { 
  3.   Schema::create('comments', function (Blueprint $table) { 
  4.     $table->increments('id'); 
  5.     $table->text('content'); 
  6.     $table->integer('item_id'); 
  7.     $table->string('item_type'); 
  8.     $table->timestamps(); 
  9.   }); 
  10. } 

↑ 这里需要指定 item_id 和 item_type 单一介绍一下 item_type 它主要是区别关联于那张表的 我们这里它只有两个值:App\Article 或 App\Video。

1.4 编写多态关联

Article 和 Video:

  1. public function comments() 
  2. { 
  3.   /** 
  4.    * 第二个参数:如果你的前缀是item_ 那么就写item 如果是别的就写别的。 
  5.    * 第三个参数:item_type 
  6.    * 第四个参数:item_id 
  7.    * 第五个参数:关联到那个表的键 
  8.    * (以上除了第二个参数都可以省略) 
  9.    */ 
  10.   return $this->morphMany(Comment::class, 'item', 'item_type', 'item_id', 'id'); 
  11. } 

Comment:

  1. public function video() 
  2. { 
  3.   /** 
  4.    * 三个参数都可以省略 不过K建议你还是写全 
  5.    */ 
  6.   return $this->morphTo('item', 'item_type', 'item_id'); 
  7. } 

使用:

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

Tags: Laravel5.1多态关联

分享到: