Laravel 如何优化仅由状态分隔的多个查询

Laravel how can optimize multi queries that separated by only statuses

现在我使用 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
    ]);

}

如何将这些要求优化为一个?

谢谢

只检索一次

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

然后用collection where method

过滤
//active
$activeItems = $items->where('status', 1);
$activeCount = $activeItems->count();

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