【问题标题】:Laravel how can optimize multi queries that separated by only statusesLaravel如何优化仅由状态分隔的多个查询
【发布时间】:2020-11-04 09:46:17
【问题描述】:

现在我使用 3 个查询得到 all itemsactive itemsinactive items 及其计数。

这是我目前获取它们的功能。

public function getItems()
{
    $items = $this->model->with('category')->latest()->get();
    $count['all'] = $items->count();
    $all = view('components.item', compact('items'))->render();

    $items = $this->model->with('category')->latest()->whereStatus(1)->get();
    $count['active'] = $items->count();
    $active = view('components.item', compact('items'))->render();

    $items = $this->model->with('category')->latest()->whereStatus(0)->get();
    $count['inactive'] = $items->count();
    $active = view('components.item', compact('items'))->render();

    return response()->json([
       'all'=>$all
       'active'=>$active,
       'inactive'=>$inactive,
       'count'=>$count
    ]);

}

如何将这些查询优化为一个?

谢谢

【问题讨论】:

    标签: php laravel eloquent query-optimization laravel-query-builder


    【解决方案1】:

    只检索一次

    $items = $this->model->with('category')->latest()->get();
    

    然后用collection where方法过滤

    //active
    $activeItems = $items->where('status', 1);
    $activeCount = $activeItems->count();
    
    //inactive
    $inactiveItems = $items->where('status', 0);
    $inactiveCount = $inactiveItems->count();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-03
      • 2023-01-22
      • 1970-01-01
      • 1970-01-01
      • 2021-09-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多