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

spoon06's avatar

Eloquent Relation

Hello,

I've some problem with eloquent relations ,what i want to do :

Ex : I've 3 tables User(id,country_id,username) , Country(id,name), Post(id,user_id,content) I want the list only of countries which have posts , is there a way to do that with Eloquent relations ?

the same of :

SELECT * FROM country 
JOIN user ON country.id = user.country_id 
JOIN post ON user.id = post.user_id
GROUP BY country.id

Thanks.

0 likes
7 replies
ctroms's avatar

You are looking for the hasManyThrough relationship. Here is a link to the docs which covers this exact example.

spoon06's avatar

Yes i tried to do this on Country Model:

public function posts()
   {
       return $this->hasManyThrough('App\Models\Post', 'App\Models\User' );
   }

but how to get the list of only countries with posts ?

ctroms's avatar
ctroms
Best Answer
Level 15

You can query for relationship existence with the 'has' method as described in this section of the docs.

$countries = App\Country::has('posts')->get();
spoon06's avatar

Thanks that exactly what i need :)

But i've an other problem now , i've a Trait global scope on the post model to add globally where conditions, when i put the global scope the returned collection is empty although the BDD request i see in the debugger is right (i tried directly in mysql).

Do you have an idea ?

Thanks again

ctroms's avatar

If you are getting the data you expect without the global scope you can remove the global scope for this specific query by using the withoutGlobalScopes method. Look for 'Removing Global Scopes' in this section of the docs.

$countries = App\Country::withoutGlobalScopes()->has('posts')->get();
ctroms's avatar

Ah. Sorry about that. That is a good package you found anyway. Glad you got it figured out.

Please or to participate in this conversation.