First off: I see this a lot here but don't really understand why you have a dedicated Model for the pivot table. In my experience you don't need it.
First I'll go into setting up the models:
class Tournament extends Model {
// Table that is associated with the model
// You don't need that if it follows convention
// but I put it here for reference
protected $table = "tournaments";
// Function you need for querying the relationship to courses
// Please note that Courses::class is PHP 5.6 only and works
// If you have a use statement for the appropriate class. If you use
// PHP < 5.6 you will need to substitute this for the fully qualified classname
// for example 'App\Models\Course'
//
// The second parameter is the name of the pivot table.
// The third parameter is the name of the foreign key for the current model
// The fourth parameter is the name of the key for the related model
// You don't have to set those if you follow convention but I included them for completeness.
public function courses()
{
return $this->belongsToMany(Course::class, 'tournament_courses', 'tournament_id', 'course_id');
}
}
We do the same for the Course model in case you want to query tournaments based on courses. (I'll spare the comments as it's the same as in the Tournament model):
class Course extends Model {
protected $table = "courses"
public function tournaments() {
return $this->belongsToMany(Tournament::class, 'tournament_courses', 'course_id', 'tournament_id');
}
}
If you want to query those relationships you have 2 options: You can use the functions or use them as dynamic properties:
$courses = $tournament->courses()->get();
$courses = $tournament->courses;
To insert a new course into a tournament you simply do this:
$course = Course::find($id); //Or whatever query you need to do to get the course
$tournament = Tournament::find(1);
$tournament->courses()->save($course);
If you want to insert multiple courses into a tournament build an array of the courses:
$courses = Courses::all(); // You have to build the array of courses according to your business needs, I use this just to illustrate
$tournament = Tournament::find(1);
$tournament->courses()->saveMany($courses);
And your pivot table migration would probably look something like this:
class CreateTournamentCoursesTable extends Migration {
public function up()
{
$this->schema->create('tournament_courses', function(Blueprint $table) {
$table->increments('id');
$table->integer('tournament_id')->unsigned();
$table->integer('course_id')->unsigned();
$table->timestamps();
$table->index('tournament_id');
$table->index('course_id');
$table->foreign('tournament_id')
->references('id')->on('tournaments')
->onDelete('cascade');
$table->foreign('course_id')
->references('id')->on('courses')
->onDelete('cascade');
});
}
}
I have not tested any of this so I can't guarantee that it works but it should. Let me know if it does and if not I'll go ahead and do some testing for you.
Best,
Marcel