如何在laravel上显示评论的文章?

时间:2015-12-14 08:59:24

标签: php laravel laravel-5 eloquent

我的关系是这样的:帖子Req.php有很多评论CommentsRequest.php,评论有很多文件FileRequest.php。如何从post的指定评论中获取文件的详细信息?

模特:

//Req.php
public function user()
{
    return $this->belongsTo('App\User', 'profil_id', 'id');
}
public function commentsRequest()
{
    return $this->hasMany('App\CommentRequest');
}

//CommentRequest.php
public function request()
{
        return $this->belongsTo('App\Req');
}
public function user()
{
    return $this->belongsTo('App\User', 'profil_id', 'id');
}
public function filesRequest()
{
    return $this->hasMany('App\FileRequest', 'comreq_id');
}

//FileRequest.php
public function commentsRequest()
{
    return $this->belongsTo('App\CommentRequest', 'comreq_id', 'id_comreq');
}

将评论存储在CommentController.php

public function store($id)
{
    $files = Input::file('filefield');
    $user = Auth::user()->id;
    $request = Req::find($id);
    $isi = Input::get('comment');
    $comment = CommentRequest::create(array('req_id' => $id, 'profil_id' => $user, 'comment' => $isi ));

    foreach($files as $file) {
        $names = "";
        $x = new FileRequest();

        if($validator->passes()){
        $destinationPath = 'uploads/request';
        $mime = $file->getClientOriginalExtension();
        $upload_success = $file->move($destinationPath, $filename);
        $names .= $filename;

        $x->filename = rand(11111,99999).'.'.$mime;
        $x->type = $mime;
        $x->original_filename = $file->getClientOriginalName();

        $comment->filesRequest()->save($x);
        }
    }

    return view('request.show', compact('request'));
}

我希望使用此代码在视图上显示文件注释但错误

  <ul>
        @foreach($request->commentsRequest as $comment)
              <h5>{{ $comment->komentar }} by {{ $comment->user->name }}</h5>
              @foreach($comments->filesRequest->all() as $file)
                    <h5>{{ $file->filename }}</h5>
              @endforeach

        @endforeach
  </ul>

如何解决这个问题?我有这个问题的堆栈。抱歉英文不好

1 个答案:

答案 0 :(得分:0)

您收到此未定义属性错误,因为您尝试从 $ comments 变量中获取 $ filesRequest 属性,这是一个收集评论。您需要从个人 $ comment

中获取它
@foreach($comment->filesRequest->all() as $file)
  <h5>{{ $file->filename }}</h5>
@endforeach

您也可以跳过对所有()的调用,因为 $ comment-&gt; filesRequest 已经返回该集合,因此以下内容应该足够了:

@foreach($comment->filesRequest as $file)
  <h5>{{ $file->filename }}</h5>
@endforeach