0

It is possible to load count of relations for already fetched model, like that:

$post->loadCount([ 'comments', 'something', 'else', ]); 

Now I want to add constraints to some counts:

$post->loadCount([ 'comments' => fn($q) => $q->where('approved', true), 'something', 'else', ]); 

Great, but now I need count for approved and not approved comments. And I'm stuck.

$post->loadCount([ 'comments' => fn($q) => $q->where('approved', true), // as comments_approved 'comments' => fn($q) => $q->where('approved', false), // as comments_pending 'something', 'else', ]); 

This of course does not work because comments is defined twice in array. Also because loadCount() expects relation name as array key, I cannot use comments_approved because this is not a relation.

Is there some other option in loadCount or different approach?

2

1 Answer 1

3

Like the withCount, you can also alias the relation name in loadCount

 $post->loadCount([ 'comments as comments_approved' => fn($q) => $q->where('approved', true), 'comments as comments_pending' => fn($q) => $q->where('approved', false), 'something' ]); 
Sign up to request clarification or add additional context in comments.

4 Comments

For your information, I am in discussions with other curators about potentially merging your answer to Why loadCount() introduced and its actual usage into laravel. Your insights would be unique and helpful on that page. That question is suitably asked as a canonical page for all new questions on the topic of loadCount(). If your answer is moved, will you be open to editing your answer to more broadly/generally explaining this implementation with aliased counts?
I believe this new question will serve as a good sign post for the older canonical page.
Hi @mickmackusa, I will be pleased to bring more details about this implementation.
I've spoken with Dharman and there will be no page merging. If you'd like to answer that older page to describe the implementation of this answer (in a generalized way), I think that would help future readers to understand how to use this method with an aliased count columns.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.