代码之家  ›  专栏  ›  技术社区  ›  jose

如何提高每个人的口才

  •  1
  • jose  · 技术社区  · 4 年前

    如何提高具有以下特征的查询的性能(这是一个模拟示例):

    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]);
    }
    

    在我的实际案例中,foreach返回了很多有性能问题的数据;

    等待时间(TTFB),即浏览器等待 响应的第一个字节几乎需要27秒

    3 回复  |  直到 4 年前
        1
  •  1
  •   medilies    4 年前
    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]);
    }
    
    

    这将导致3个查询,输出如下:

    [
      // item 0 ...
      [
        // item data
        [
          // games
        ],
        [
          // players
        ]
      ],
    
      // other items
    ]
    
        2
  •  1
  •   kingan    4 年前

    干得好

    public function getData() 
    {
        $items = Item::with('games.players')->orderBy('id_item', 'DESC')->get();
        
        return response()->json(['success'=>true, 'items'=>$items]);
    }
    
        3
  •  0
  •   Dennis    4 年前

    基于代码的解决方案:

    • 在阵列上循环大约比在列表上循环便宜2倍。
    • “for”循环比“foreach”快得多

    另一个解决方案是:

    • 过滤不必要的部分以运行循环
    推荐文章