Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 1 year ago.
0

I found that using hasManyThrough I can access for example all the Users in a State, but I don't know how to chain the relationships to get all users in country

Last updated 1 year ago.
0

This might work but I haven't tried it. But since States have a country_id you should be able to use hasManyThrough and pass a country_id condition.

class States extends Eloquent{
    protected $table = 'states';

    public function users() {
        return $this->hasManyThrough('City', 'User', 'id', 'user_id')
    }

    public function usersByCountry($country_id) {
        return $this->hasManyThrough('City', 'User', 'id', 'user_id')->where('country_id', '=', $country_id)
    }

}


//display all users by country
$countries = Countries::all();
foreach($countries as $country) {
  $user_of_country = State::usersByCountry($country->id)
  foreach ($user_of_country as $the_user) {
    echo $the_user->name . '<br />';
  }
}

I am not sure I have the hasManyThrough definition right but you already have that working... just create another one that passes in a country_id.

Last updated 1 year ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.