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

Shizu's avatar
Level 1

Multiple relationships count

Hello,

I have models : Country, Agency, Student.

Student hasOne Agency. Agency hasMany Student. Agency hasOne Country. Country hasMany Agency.

I want to count Student by Country. And if is possible, i want to groupBy students by gender and by country.

Other exemple :

I have these models : Contract, Level, Formation, Student.

Student hasMany Formation. Formation hasOne Student. Formation hasOne Contract. Formation hasOne Level. Contract hasMany Formation. Level hasMany Formation.

I don't know how to count students by contract and by level.

Can you help me with this problem ?

Thanks you

0 likes
2 replies
tim_jespers's avatar
Level 3

Hi! For the first problem you're facing you can use a hasManyThrough on the Country model:

//country.php
public function students(){
    return $this->hasManyThrough('App\Agency','App\Student');
}

//count students by country:
$studentsCount = $country->students()->count();

//get students for country
$students = $country->students;
Shizu's avatar
Level 1

Hi !

It's perfect ! But, according with laravel docs: "the first argument passed to the hasManyThrough method is the name of the final model we wish to access...."

In my case is :

public function students() {
    return $this->hasManyThrough('App\Student','App\Agency');
} 

=> https://laravel.com/docs/5.4/eloquent-relationships#has-many-through

Thanks you for your answer !!

Please or to participate in this conversation.