laravel的union all求聚合

//出库
        $outstockQuery = $this->getOutstockContentQuery($hqCode, $startDate, $endDate, $orgzIds, $typesIn, $productCategory, $onTheWay, $searchType, $keyword, $orderBy, $sort, $length, $offset, $settlementDate);

        //入库
        $InStockContentModel = new InStockContentModel();
        $instockQuery = $InStockContentModel->getInstockContentQuery($hqCode, $startDate, $endDate, $orgzIds, $typesOut, $productCategory, $onTheWay, $searchType, $keyword, $orderBy, $sort, $length, $offset, $settlementDate);

        $unionQuery = $outstockQuery->unionAll($instockQuery);
        $query = clone $unionQuery;

        $summary = DB::table( DB::raw("({$query->toSql()}) as t") )
            ->mergeBindings($query->getQuery())
            ->select(DB::raw('SUM(quantity) as quantity'),
                DB::raw('SUM(amount) as amount'),
                DB::raw('COUNT(*) as total'))
            ->first();

        $result = ['list'=> [],'summary'=>[],'total'=>0];
        $result['total'] = $summary->total??0;
        if ( $result['total'] == 0 ){
            return $result;
        }

        $summary = $summary ? array($summary) : ['quantity'=>0,'amount'=>0];