调用未定义的方法 App\Post::withCount()

Call to undefined method App\Post::withCount()

我找不到问题出在哪里。我有 postscomments table。在 commentstable 中我添加了 foreign key post_id。现在我想在收到所有帖子时同时统计评论数。

这是我的 PostController

public function show_api()
{
   return $this->withCount('comments')->get();
}

public function comments()
{
    return $this->hasManyThrough(Comment::class);
}

CommentController

public function post()
{
    return $this->belongsTo(Post::class);
}

我的错误在哪里?

在这种情况下,你应该使用hasMany关系:

class Post extends Model
{
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

那么这将起作用:

Post::withCount('comments')->get();

我认为您已经在控制器而不是模型中定义了这些关系。 您应该在各自的模型中定义这些关系,然后它应该可以工作。