Reputation: 15
I have 4 tables :
User
Country
Post
Cities
User belongs to Country and User also belongs to Post !
I wish to be able to find all users that have at least one post and exists in at least one country and city
Is it possible using only Eloquent relationships like described here ? What about polymorphic relationship ?
https://laravel.com/docs/9.x/eloquent-relationships#one-to-many-polymorphic-relations
Upvotes: 0
Views: 498
Reputation: 130
Above answer is true and no need to using polymorphic relationship here.
Polymorphic relationship used when some models are related to one model for example consider Post and Article models. To allow for comments on each of these, we can decide to set up polymorphic relationship.
Upvotes: 0
Reputation: 1682
You don't even need to use a polymorphic relation for that.
I believe that you have a post_id
and a country_id
column in the User
table.
Also I believe you have the following relationships in the User
model:
public function country()
{
return $this->belongsTo(Country::class);
}
public function post()
{
return $this->belongsTo(Post::class);
}
After that you can easily make your condition using eloquent model:
User::whereHas('post')->whereHas('country')->get();
Upvotes: 1