Skip to content
Advertisement

How to improve eloquent nested foreach performance

How can I improve the performance of a query with the following characteristics (this is a simulation to exemplify):

public function getData() 
{
    $itens = Item::orderBy('id_item', 'DESC')->get();

    foreach($itens as $item){
        $item->games = $item->games()->get();

        foreach( $item->games as $player){
            $item->players = $player->players()->get();
        }
    }
    
    return response()->json(['success'=>true, 'itens'=>$itens]);
}

In my real case, the foreach returns a lot of data with performance problems;

The Waiting (TTFB), that is, the time the browser is waiting for the first byte of a response, takes almost 27s

Advertisement

Answer

class Item extends Model{
  // ...

  public function games(){
    return this->hasMany(Game::class);
  }

  public function players(){
    return this->hasManyThrough(Player::class ,Game::class);
  }
}
public function getData() 
{
    $itens = Item::orderBy('id_item', 'DESC')->with('games','players')->get();
    
    return response()->json(['success'=>true, 'itens'=>$itens]);
}

That will result in 3 queries and the output will be like:

[
  // item 0 ...
  [
    // item data
    [
      // games
    ],
    [
      // players
    ]
  ],

  // other items
]
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement