2017-02-01 3 views
0

며칠 전 사용자가 게시물에 댓글을 쓸 수있는 웹 사이트를 보았습니다. 다른 사용자가 이에 응답 할 수 있습니다. 리플레이는 아래 예제 스크린 샷과 같은 대답을 가질 수 있습니다. enter image description herelaravel 설득력있는 중첩 된 댓글 및 응답

그래서 나는 그것을 시도해 보려고했지만 어떻게 든 그것을 이해할 수 없었습니다. 여기 내 데이터베이스는

$comments = Comment::with('replies')->where('reply_id','=',0)->get(['id','reply_id','body']); 
    return response($comments); 

이 완벽하게 주석 및 응답을 반환 컨트롤러

에서 모델

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

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

    public function post() 
    { 
     return $this->belongsTo(Post::class); 
    } 

    public function replies() 
    { 
     return $this->hasMany(Comment::class,'reply_id','id'); 
    } 

에서

Schema::create('comments', function (Blueprint $table) { 
      $table->increments('id'); 
      $table->unsignedInteger('user_id'); 
      $table->unsignedInteger('post_id'); 
      $table->unsignedInteger('reply_id')->default(0); 
      $table->text('body'); 
      $table->timestamps(); 
     }); 

관계를 설정합니다. 그러나 회신의 회신이 있다면, 그것은 나타나지 않습니다. 어떻게해야합니까? 제안이 필요합니다.

답변

2

스왑 reply_idnullable()parent_id. 따라서 기본적으로 댓글에 부모가 있는지 알고 싶습니다.

그런 다음 Comment 모델에서 자기 관계를 추가하여 parent_id과 일치하는 모든 의견을 가져옵니다. 보기에

public function replies() { 
    return $this->hasMany('App\Comment', 'parent_id'); 
} 

각 의견 루프의 응답을 중첩 한 수

@foreach($comments as $comment) 
    {{ $comment->content }} 

    @if ($comment->replies) 
     @foreach($comment->replies as $rep1) 
      {{ $rep1->content }} 
      ... 
     @endforeach 
    @endif 
@endforeach