问题描述
我正在尝试获取评论,并且它在laravel API中得到答复,我尝试按照以下方式处理,并遇到此错误,该如何解决? 这是我的控制器:
public function postSinglePage(Request $request)
{
$post_id=$request->get('post_id');
$post = Post::where('id',$post_id)->where('status','=',1)->get();
return response([
"posts" => GetPostsSinglePageData::collection($post),]);
}
这是我要发布的资源集及其评论:
public function toArray($request)
{
return [
'post_id' => $this->id,"name" => $this->post_title,"excerpt" => $this->post_excerpt,"thumbnail" => $this->getFirstMediaUrl("images"),"logo" => $this->getFirstMediaUrl("images"),'comment_count'=>getCommentCount($this->id),'comments'=> new CommentCollection(Comment::select('*')->where('post_id',$this->id)),"like" => DB::table("like_tb")->select('like_dislike')
->where("type_like",'post')
->where('related_id',$this->id)
->get(),"share" => DB::table("share_tb")->select("share_number")
->where('type','post')
->where("related_id",];
}
这是评论集:
public function toArray($request)
{
return [
'commentId'=>$this->id,'courseId'=>$this->post_id,'commentDate'=>$this->date,'commentText'=>$this->body,'userId'=>$this->user_id,'replays'=>ReplyCommentCollection::collection(\App\Models\Comment\ReplyComment::where('comment_id',$this->id)->get()),'users'=>UserInfoCollection::collection(User::where('id',$this->user_id)->get()),];
}
解决方法
$ this-> id 在其他内部函数中不起作用,您必须这样编写:
public function toArray($request)
{
$comments=Comment::select('*')->where('post_id',$this->id)->get();
$commentCollection= CommentCollection::collection($comments);
return [
'post_id' => $this->id,"name" => $this->post_title,"excerpt" => $this->post_excerpt,"thumbnail" => $this->getFirstMediaUrl("images"),"logo" => $this->getFirstMediaUrl("images"),'comment_count'=>getCommentCount($this->id),'comments'=> $commentCollection,"like" => DB::table("like_tb")->select('like_dislike')
->where("type_like",'=','post')
->where('related_id',$this->id)
->get(),"share" => DB::table("share_tb")->select("share_number")
->where('type','post')
->where("related_id",];
}