Home > Software engineering >  Make eloquent custom relationship
Make eloquent custom relationship

Time:06-11

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

CodePudding user response:

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();
  • Related