多态关联问题,评论功能实现

现有两个模型文章(Post)评论(Comment),模型定义如下

  1. Post

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use YuanChao\Editor\EndaEditor;

class Post extends Model
{
    protected $fillable = ['user_id', 'title', 'content'];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable')->orderBy('created_at', 'desc');
    }
}
  1. Comment

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use YuanChao\Editor\EndaEditor;

class Comment extends Model
{
    protected $fillable = ['user_id', 'commentable_id', 'commentable_type', 'body'];

    /**
     * Get all of the owning commentable models.
     */
    public function commentable()
    {
        return $this->morphTo();
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * 子集评论
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphMany
     */
    public function comments()
    {
        return $this->morphMany(self::class, 'commentable')->orderBy('created_at', 'desc');
    }
}

如上所示一篇文章可以有多个评论,每个评论又可以有多个子评论,我遇到的问题是在模板渲染时可以通过“渴求势加载”方式在模板页嵌套循环输出评论。但是我现在要使用VUE把评论做成一个模块,需要请求得到评论的tree型结构,这个有什么好的处理方式吗

GOD_Nt

解决了,竟然可以这么简单

746019546 回复 GOD_Nt

你好,可以分享一下怎么做的么?我用了buam,我也想实现树型数据输出

GOD_Nt 回复 746019546

直接在关联的后面加with(‘childrens’) childrens是你的子关联函数

foxriver123 回复 GOD_Nt

楼主方便上个代码吗!谢谢

siwei1

请问一下多态关联怎么插入主表数据,比如视频表和文章表都有评论,怎么往视频插入评论数据,由于用的多态关联,评论数据在第三表