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

6ber6ou's avatar

belongsToMany and count

Hi all,

I have 3 tables : - agencies - categories - agency_category (pivot table)

In the models Agency.php and Category.php I have set a belongsToMany relationship. Now I want to know the percentage of agencies in each category. How can I do ?

0 likes
3 replies
bart's avatar

What about using the count() method?

$categories = Categories::with('agencies')->get();
$amount = Agency::all()->count();

foreach($categories as $category) {
    echo 'Percentage: ' . $category->agencies()->count() / $amount * 100 . "%\n";
}
1 like
bestmomo's avatar

Or a solution with one query :

$result = Agency::join('agency_category', 'agency_category.agencies_id', '=', 'agencies.id')
    ->groupBy('agencies.id')
    ->get(['agencies.*', DB::raw('COUNT(agency_category.id) * 100 / (SELECT COUNT(*) FROM categories) as count')]);

foreach ($result as $r) {
    echo $r->id . '   ' . $r->count . '%<br>';
}

Hum I think I made the inverse of your purpose but the principe is good ;)

nolros's avatar

math is :

percent of agencies in a category = ( #agencies in a category / all agencies) * 100

Please or to participate in this conversation.