Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

yulquen's avatar

Counting a pivot table associations

Hey folks!

I'm trying to get my head around a specific sql query to build with eloquent relationships.

I have 3 tables:

  • articles
  • tags
  • article_tag (pivot table)

I want to run a query to get a collection, that contains only those tags, that are associated with at least one article including the article count for each tag.

The raw query would something like this:

select t.id, t.key, t.name, count(pivot.tag_id) as article_count from tags AS t INNER JOIN article_tag AS pivot ON t.id = pivot.tag_id GROUP BY t.id ORDER BY article_count, t.name;

Right now, i have this in my tag repository:

return $this->model->whereHas('articles', function ($q)
{
    $q->online();
})->get();

online() is just a query scope on the article model that filters articles that are already published. With that query i already get the tags, but i'm missing the count for each one.

Can anyone get point me in the right direction, to change the query that i also get the amount of associated articles?

Thanks :)

0 likes
0 replies

Please or to participate in this conversation.