1

我正在尝试获得评论,它在 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",$this->id)
            ->get(),

    ];
}

这是评论集:

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()),
    ];
}
4

1 回答 1

1

$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",$this->id)
                ->get(),

        ];
    }
于 2020-09-19T14:37:01.703 回答