Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying many-to-many relationship in Laravel while limiting relation existence

I have the following models in laravel:

TheJobs
- id
- description
- created_at
- deleted_at
- updated_at

TheSeries
- id
- title
- description
- created_at
- deleted_at
- updated_at


TheMovies
- id
- title
- description
- created_at
- deleted_at
- updated_at


mSeriesJobs
- seriesID
- jobID

mMoviesJobs
- movieID
- jobID

Here are the relationships for TheJobs:

 public function TheSeries() {
    return $this->belongsToMany('App\Models\TheSeries', 'mSeriesJobs', 'jobID', 'seriesID');
  }

  public function TheMovies() {
    return $this->belongsToMany('App\Models\TheMovies', 'mMoviesJobs', 'jobID', 'movieID');
  }

Here are the relationships for TheSeries:

  public function TheJobs() {
    return $this->belongsToMany('App\Models\TheJobs', 'mSeriesJobs', 'seriesID', 'jobID');
  }

same for Movies.

I would like to :

  • get all TheSeries jobs.
  • get all TheMovies jobs.
  • get all the Jobs with TheSeries or TheMovies data.

To clarify the question:

I need a simple Eloquent query which will select all TheSeries which have at least one TheJobs.

like image 241
Coder Avatar asked Feb 20 '17 10:02

Coder


1 Answers

From what I gathered, I believe you are looking for "Querying Relationship Existence", i.e. (wording from Laravel Doc) accessing the records for a model, while limiting the results based on the existence of a relationship.

In this case, if you need a simple Eloquent query which will select all TheSeries that have at least one TheJobs, I believe you can try has:

$TheSeries = App\TheSeries::has('TheJobs')->get();

The other way should work too, for jobs:

$TheJobs = App\TheJobs::has('TheSeries')->get();

Assumption: all model relations have been properly defined.

You can find more about "has" here: https://laravel.com/docs/5.4/eloquent-relationships (Search in-page for "Querying Relationship Existence" please.)

like image 166
hktang Avatar answered Oct 21 '22 04:10

hktang