Laravel |重用查询变量而不是查询重复

Laravel | Reuse Query Variable instead of query duplication

我正在尝试重用查询变量,但看起来它采用的是最后分配的值而不是原始值,这就是我的意思:

$categories = DB::table('invoice_detail')
            ->selectRaw('SUM(qty) as qty')
            ->where('loc_id', '=', $user->loc_id)
            ->join('items', 'invoice_detail.item_id', 'items.barcode')
            ->where('items.active', '1')
            ->join('categories', 'items.category_id', 'categories.id')
            ->addSelect('categories.name')
            ->groupBy('categories.name');
        dump($categories->get()); //It returns whole products, which is OK.
        $topCategories  = $categories->orderBy('qty', 'DESC')->take(5)->get();
        dump($categories->get()); // It returns the top products, not the original value.
        $downCategories = $categories->orderBy('qty', 'ASC')->take(5)->get();

我想重复使用 $categories 变量来获取 Top ProductsDown Products 而无需重复查询。

但是在第一个转储中,它 returns 整个产品,这没问题,然后在获得 Top Products 之后,它 returns 顶级产品,而不是原始值。

有什么建议吗?

您总是可以使用 __clone 方法为某个对象创建 copy 当且仅当该对象实现了 __clone 方法 :

$topCategories= clone $categories;
$topCategories->orderBy('qty', 'DESC')->take(5)->get();
$downCategories = clone $categories;
$downCategories->orderBy('qty', 'ASC')->take(5)->get();