Mike_NotGuilty
Mike_NotGuilty

Reputation: 2395

Laravel - HasOneThrough with composite primary key

I'm working on an application where persons can view sport games. The tables have composite primary keys. Here is how the relevant attributes of the tables look like:

| Game                      | Team        | League_Team    |
|---------------------------|-------------|----------------|
| id (PK)                   | id (PK)     | league_id (PK) |
| league_id (PK)            | name        | team_id (PK)   |
| home_id  (season_team_id) | ...         | season_team_id |
| guest_id (season_team_id) |             | ...            |
| ...                       |             |                |
| ...                       |             |                |

So my goal is to get all games together with the specific home and guest team... so it should look like this Game::with('homeTeam')->with('guestTeam')->....;

How is it possible to get this kind of relation? I tried hasOneThrough, but I don't know how it works with composite primary keys!

Thanks for your help!

EDIT

Models are all empty except of the $primaryKey attribute.

Game Model

protected $primaryKey = ['id', 'league_id']; public function homeTeam() { // ... }

public function up()
{
    Schema::create('basketball_games', function (Blueprint $table) {
        $table->unsignedInteger('id');
        $table->unsignedInteger('league_id')->nullable();
        $table->dateTime('date');
        $table->unsignedInteger('home_id');
        $table->unsignedInteger('guest_id');


        $table->primary(['id','league_id']);

        // Foreign Keys
        $table->foreign('league_id')->references('id')->on('basketball_leagues');

        $table->timestamps();
    });
}

Team Model

Empty

public function up()
{
    Schema::create('basketball_teams', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
    });
}

League_Team

protected $primaryKey = ['league_id','team_id'];

public function up()
{
    Schema::create('basketball_league_teams', function (Blueprint $table) {
        $table->unsignedInteger('league_id');
        $table->unsignedInteger('team_id');
        $table->unsignedInteger('season_team_id');
        $table->string('name');
        $table->timestamps();

        $table->primary(['league_id','team_id']);

        // Foreign Keys
        $table->foreign('league_id')->references('id')->on('basketball_leagues');
        $table->foreign('team_id')->references('id')->on('basketball_teams');
    });
}

Upvotes: 0

Views: 124

Answers (0)

Related Questions