withCount() doesn't include deleted rows?

2019-09-16 02:01发布

问题:

How can I make withCount('comments') also include all deleted/trashed rows?

For example, if I have 5 comments, and I delete 1, I still expect withCount('comments') to return 5, but instead it's returning 4.

My full query looks something like this:

$query = Post::withTrashed()
    ->withCount('comments')
    ->get();

回答1:

You can use the withTrashed method:

>withTrashed()


回答2:

I think you can try this

$query = Post::withCount('comments')
    ->withTrashed()
    ->get();

OR

$query = DB::table('post')
         ->select('comments', DB::raw('count(*) as comments'))
         ->get();

Hope this work for you!