问题
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!
回答3:
Since laravel doesn't propose a way to filter the relation when using withCount
, a clean solution would be to declare the relation and add the withTrashd()
to it.
In Post.php
public function commentsWithTrashed()
{
return $this->comment()->withTrashed();
}
Now you can use the withCount
on it.
$query = Post::withTrashed()
->withCount('commentsWithTrashed')
->get();
来源:https://stackoverflow.com/questions/44551311/withcount-doesnt-include-deleted-rows