Bruno Francisco
Bruno Francisco

Reputation: 4238

Access a model through an intermediate relationship

I would like to retrieve the model games using the giveaway model

giveaway:
id

giveaway_games:
id
gameID
giveawayID

games:
id
name

Reading the docummentation I understood I have to use the hasManyThrough relationship but I'm not sure if I'm using it correctly

public function gamesNames(){
    return $this->hasManyThrough(Games::class, GiveawayGames::class, 'gameID', 'id');
}

Any help would be greatly appreciated.

Upvotes: 0

Views: 57

Answers (1)

common sense
common sense

Reputation: 3912

The games table need a foreign key to giveaway_games. In the following example I stick to Laravel default using _id suffix for foreign key fields.

Class:

class GiveAway 
{
    public function games()
    {
        return $this->hasManyThrough(Games::class, GiveawayGames::class);
    }
}

As a mnemonic you could read the hasManyThrough as:

GiveAway has many Games through GiveawayGames

or more abstract:

Model has many Parameter 1 through Parameter 2


Schema:

giveaway:

  • id
  • name

giveaway_games:

  • id
  • giveaway_id

games:

  • id
  • name
  • giveaway_games_id

Note for custom names for foreign keys:

If you are forced to customize the name of the foreign key like using giveawayID instead of giveaway_id, you can specify the custom name as the 3rd parameter of the hasManyThrough() method:

return $this->hasManyThrough(Games::class, GiveawayGames::class, 'giveawayID');

If you additionally customized the name of the id field, lets say to uuid you can specify this in the 4th parameter:

return $this->hasManyThrough(Games::class, GiveawayGames::class, 'giveawayID', 'uuid');

Upvotes: 1

Related Questions