Search code examples
phplaraveleloquent

Laravel Eloquent loadCount() with multiple same relations


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?


Solution

  • 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'
      ]);