如何显示带有评论的用户名和照片的评论

时间:2018-11-22 05:34:03

标签: laravel eloquent laravel-5.6

我正在尝试显示用户名称以及他们的评论,因为Tour不属于用户,因此我在这里面临[用户]问题。无法通过注释传递用户信息。在我的代码中,我只能显示属于游览的评论,而不能显示发表评论的用户。

  

游览

class Tour extends Model{

protected $table = 'tour';

public function disTour()
{
    return $this->hasMany('App\District');
}

public function review()
{
    return $this->hasMany(TourReview::class);
}

  

TourReview模型

class TourReview extends Model{

protected $table = 'tour_review';

public function tour()
{
    return $this->belongsTo('App\Tour');
}

public function user()
{
    return $this->belongsTo('App\Users');
}

  

用户模型

class Users extends Model{

protected $table = 'users';

public function userBlogs()
{
    return $this->hasMany('App\Blog');
}

public function tourReview()
{
    return $this->hasMany('App\TourReview');
}

  

控制器

public function singleDetails($id)
{
    $tour = Tour::find($id);

    $comments = Tour::find($id)->review;
    $users = TourReview::with('user')->where('id', $comments->pluck('id'))->get();
    foreach ($users as $user){
        dd($user);
    }
    //$blogs = Blog::with('images')->where('user_id', $user_id)->paginate(10);
    dd($comments);
    return view('Tours.single_tour')
        ->with(compact('tour', 'comments'));
}
  

刀片视图

@foreach($comments as $comment)
    <div class="review_strip_single">
        <img src="{{asset('wanna show commented user photo')}}" height="78" width="78" alt="Image"  class="img-circle">
         <small> - {{$comment->created_at->format('d M Y')}} -</small>
         <h4>{{wanna show user name}}</h4>
            <p>  {{$comment->tourreview_desc}}    </p>
     </div>
@endforeach

1 个答案:

答案 0 :(得分:0)

  

您可以在控制器中进行嵌套查询

public function singleDetails($id)
{
    $tour = Tour::with(['review.user'])->find($id);

    return view('Tours.single_tour')
        ->with(compact('tour'));

或者如果您只想评论

$comments = Review::with('user')->whereHas('tour', function ($q)use($id){
             $q->where('id', $id);
     });

    return view('Tours.single_tour')
        ->with(compact('comments'));
}
  

刀片视图

 @foreach($tour->comments as $comment)
         <div class="review_strip_single">
             <img src="{{asset('wanna show commented user photo')}}" height="78" width="78" alt="Image"  class="img-circle">
                 <small> - {{$comment->created_at->format('d M Y')}} -</small>
                 <h4>{{$comment->user->name}}</h4>
                   <p>  {{$comment->tourreview_desc}}  </p>
         </div>
   @endforeach

 @foreach($comments as $comment)
     <div class="review_strip_single">
         <img src="{{asset('wanna show commented user photo')}}" height="78" width="78" alt="Image"  class="img-circle">
            <small> - {{$comment->created_at->format('d M Y')}} -</small>
            <h4>{{$comment->user->name}}</h4>
            <p>  {{$comment->tourreview_desc}}  </p>
     </div>
   @endforeach