withCount() doesn't include deleted rows?

谁说胖子不能爱 提交于 2019-12-11 16:47:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!