如何显示特定帖子的评论?

时间:2018-03-21 16:18:34

标签: php laravel laravel-5

我想为我网站上的每项特定服务显示评论。 商店评论方法工作正常! 当我尝试在刀片页面中显示评论时,我收到此错误

  

SQLSTATE [42S22]:未找到列:1054未知列' comments.service_id'在' where子句' (SQL:select {from comments其中commentsservice_id = 11和commentsservice_id不为空)(查看:C:\ xampp \ htdocs \ dawerelzirou \资源\视图\服务\ showservice.blade.php)

CommentsController.php(商店评论)

public function store(Request $request,  $services_id)
{
   $this->validate($request,array(
        'body'=>'required',
    ));


  $comment=new Comment;

  $comment->body=$request->body;
  $comment->user_id=$request->user()->id;
  $comment->services_id=$services_id;
  $comment->save();



  $request->session()->flash('notif','success');
  return back();
}

这是Comment.php

         class Comment extends Model{ 


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



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

                         }

这是Service.php

     class Service extends Model{




public function user(){

    return $this->belongsTo('App\User');
}

public function comments(){
    return $this->hasMany('App\comment');

}
       }

刀片页面:

@if (count($services->comments)>0)

       @foreach ($services->comments as $comment)
            <div class="row">
            <div class="col s6 offset-l3">
            <div class="card small" style="height:auto;width:700px;">
            <div class="card-content center-align">
            <div class="row">
            <div class="col s12">
        <img src="/img/bg.jpeg" class="responsive-img circle center-align" 
        style="width:50%;" alt="">
        </div>
       <div class="row">
       <div class="col s12">
     <p>$comment->user->username </p>
       </div>
       </div>
        <br>
       <div class="row">
       <div class="col s12">
       <p>$comment->body</p>
           </div>
           </div>
           </div>
          </div>

          </div>
          </div>
          </div> 
       @endforeach
          @endif

2 个答案:

答案 0 :(得分:2)

如果你没有使用命名约定,那么在laravel中建立关系时总是添加适当的本地和外键,因为laravel使用snakecase命名转换

答案 1 :(得分:1)

Laravel具有特定的命名约定 - 您的列应为service_id,而不是services_id。由于您使用该命名约定,您需要告诉关系要查看的列:

return $this->hasMany('App\comment', 'services_id');

另请注意,在某些具有区分大小写的文件名的操作系统上,App\CommentApp\comment是不同的。确保您使用正确的大小写 - App\Commentclass CommentComment.php App\comment,{{1} }和class comment。不是混合!