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

发布时间:2021-04-13 15:55:16 作者:Leah
来源:亿速云 阅读:117

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

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

推荐阅读:
  1. Laravel5.1框架关联模型之后怎么用
  2. Laravel5.1框架模型远层一对多关系的示例分析

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

laravel5.1

上一篇:使用Laravel5.1 框架怎么实现一个登录和注册功能

下一篇:使用Laravel5.1 框架怎么实现一个分页展示功能

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》