使用Laravel5.1 框架怎么实现模型多态关联

2023-06-06

使用Laravel5.1 框架怎么实现模型多态关联?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

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;
  }
});

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注本站行业资讯频道,感谢您对本站的支持。

《使用Laravel5.1 框架怎么实现模型多态关联.doc》

下载本文的Word格式文档,以方便收藏与打印。