加入收藏 | 设为首页 | 会员中心 | 我要投稿 聊城站长网 (https://www.0635zz.com/)- 智能语音交互、行业智能、AI应用、云计算、5G!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

什么是 Laravel中的多态相关,如何实现多态关联?

发布时间:2023-06-23 15:21:02 所属栏目:PHP教程 来源:
导读:在这篇文章中,我们来学习一下“Laravel中多态关联是什么,怎样实现的?”的相关知识,下文有详细的讲解,易于大家学习和理解,有需要的朋友可以借鉴参考,下面就请大家跟着小编的思路一起来学习一下吧。
在这篇文章中,我们来学习一下“Laravel中多态关联是什么,怎样实现的?”的相关知识,下文有详细的讲解,易于大家学习和理解,有需要的朋友可以借鉴参考,下面就请大家跟着小编的思路一起来学习一下吧。
 
什么是多态关联? 一个例子你就明白了:好比如说评论 它可以属于视频类 也可以属于文章类,当有个需求是 从评论表中取到视频类的数据,这就需要用到多态关联了。
 
简单的一句话总结:一张表对应两张表。
 
1 实现多态关联
 
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 它主要是区别关联于那张表的 我们这里它只有两个值:App\Article 或 App\Video。
 
1.4 编写多态关联
 
Article 和 Video:
 
  public function comments()
 
  {
 
    /**
 
     * 第二个参数:如果你的前缀是item_ 那么就写item 如果是别的就写别的。
 
     * 第三个参数:item_type
 
     * 第四个参数:item_id
 
     * 第五个参数:关联到那个表的键
 
     * (以上除了第二个参数都可以省略)
 
     */
 
    return $this->morphMany(Comment::class, 'item', 'item_type', 'item_id', 'id');
 
  }
 
Comment:
 
  public function video()
 
  {
 
    /**
 
     * 三个参数都可以省略 不过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;
 
  }
 
});
 
 

(编辑:聊城站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!