crowley
crowley

Reputation: 23

laravel three one to many relations

I learn and I want to create in laravel something like a kind of movie library. I have three tables:

Series, series_seasons, series_espisodes

Series model:

public function series_seasons()
{
    return $this->hasMany('App\SeriesSeason','series_id');
}

Seasons model:

public function series_episodes()
    {
        return $this->hasManyThrough('App\SeriesEpisode','App\SeriesSeason','series_id','season_id');
    }

 public function series()
    {
        return $this->belongsTo('App\Series','series_id');
    }

(initially instead 'hasManyThrough' I had 'hasMany')

episodes model:

public function series_season()
{
    return $this->belongsTo('App\SeriesSeason','season_id');
}

So my question is how can I get: series->series_seasons->all episodes of a specific season ?

Upvotes: 2

Views: 69

Answers (1)

Ognjen Stefanovic
Ognjen Stefanovic

Reputation: 404

You can add field season_id in your series_espisodes table. Then you can retrieve all of them like this:

$allEpisodes = Episodes::where('season_id', $seasonID);

You can add series_id field as well, and then you can retrieve all of it like this:

$allEpisodes = Episodes::where(['season_id'=> $seasonID, 'series_id => $seriesID]);

This would be the easiest way of doing this, without making any complicated logic behind it. And you have everything in there. If you create it right, you can skip seasons table, because it's only a number. So you can have two tables, one for the series and one for the episodes. Simple and effective.

Upvotes: 1

Related Questions