Laravel treat pivot table as model with relations

时间:2015-07-28 16:14:42

标签: php laravel laravel-5 many-to-many pivot

I am new to laravel and still a little bit confused about relations.

I have two models: Tournament and Season with many to many relations.

Schema::table('tournaments', function(Blueprint $table)
{
    $table->increments('id')->unsigned();
    $table->string('name')->unique();
});

Schema::table('seasons', function(Blueprint $table)
{
    $table->increments('id')->unsigned();
    $table->string('name')->unique();
});

and the pivot table

Schema::table('season_tournament', function(Blueprint $table)
{
    $table->integer('season_id')->unsigned();
    $table->integer('tournament_id')->unsigned();
    $table->primary(['season_id','tournament_id']);
});

And relations described in Models like

//Tournament model
public function seasons()
{
    return $this->belongsToMany('App\Season');
}

//Season model
public function tournaments()
{
    return $this->belongsToMany('App\Tournament');
}

And everything works perfect until I need to add a new model - Event, with next relations: Any tournament in any season can have separate events. So each season_tournament record can have many events, and each event should belongs to exact season_tournament record. So when I run the next code:

Tournament::first()->seasons()->latest()->first()->events;

I should not get all events from the whole season, but from pair tournament_season.

So basically it looks like I need extended pivot with 3 columns like:

Schema::table('event_season_tournament', function(Blueprint $table)
{
    $table->integer('event_id')->unsigned();
    $table->integer('season_id')->unsigned();
    $table->integer('tournament_id')->unsigned();
    $table->primary(['event_id','season_id','tournament_id']);
});

Is there any built-in methods to manage such things? Or maybe there are more simple solutions?

0 个答案:

没有答案
相关问题