Get data through pivot table in Laravel

  laravel, pivot

I got 3 tables. Table 1 & 2 has their ids as foreign keys in third one(pivot).

Relations for first one is

$this->hasMany("AppPivot","game_id");

, second is

$this->belongsToMany("AppPivot","army_id");

and pivot has relationships with both of them i.e belongsTo.

My schema:
schema

I tried accessing it in controller of first one like this:

$games= Game::with("armies")->get();

armies

Result that i get is array of games where instead of individual army data , i get collection from pivot table.

I can loop through it and get it that way, is there more elegant way of doing it?

Source: Laravel

Leave a Reply