I saw the following issues related to withCount: https://github.com/yajra/laravel-datatables/issues?utf8=%E2%9C%93&q=withcount but I'm still not sure how to implement orderable counts of related model:
I have Article model with the following Polymorphic relationship:
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
In ArticleController there is the following method for processing DataTables ajax requests:
public function process()
{
$articles = Article::withCount('comments')->with(['market', 'category', 'user'])->select('articles.*');
return Datatables::of($articles)
. . .
->editColumn('comments_count', function ($article) {
return $article->comments_count;
})
. . .
->rawColumns(['title', 'image_path', 'approved', 'action', 'body'])
->make(true);
}
... and finally there is a blade view file with the following DataTables setup:
table.DataTable({
. . .
columns: [
. . .
{ data: 'comments_count', name: 'comments_count', className: "text-center", searchable: false },
. . .
]
. . .
This doesn't work, even numbers are not shown:

But when I remove withCount('comments') and eager-load comments:
$articles = Article::with(['market', 'category', 'user', 'comments'])->select('articles.*');
... and edit column like this:
->editColumn('comments_count', function ($article) {
return $article->comments->count();
})
... the counts of comments are shown but are, of course, not orderable. I saw that:
If you are counting from relations, you then need to do some
joinstatements. The key here is as long as it works on the SQL level, it should work with dataTables.
So I guess that I would need to remove eager loading of comments but, as for the counting on SQL level, I'm not sure how to do it in my case where I am using Eloquent DataTables Class and how that SQL would look like here:
$articles = Article::with(['market', 'category', 'user'])->select('articles.*');
You need to perform select first before doing the count.
$articles = Article::select('articles.*')
->withCount('comments')
->with(['market', 'category', 'user']);
@yajra Thanks, that worked! However, I've encountered another problem: When having withCount & where at the same time - the results are not paginated and ordering doesn't work. I've opened new Issue where are more details about that.
Most helpful comment
You need to perform select first before doing the count.