Laravel嵌套子查询

$hq_code = $params['hq_code'];
        $orgz_ids = $params['orgz_ids'];
        $product_ids = $params['product_ids'];
        $start_date = $params['start_date'];
        $end_date = $params['end_date'] ?? date('Y-m-d');//区间最多保持1年

        $sub = DB::table('stock_change_record')->selectRaw('max(created_at) as created_at')
            ->where('hq_code',$hq_code)
            ->whereIn('orgz_id',$orgz_ids)
            ->whereIn('product_id',$product_ids)
            ->whereBetween('created_at',[$start_date,$end_date])
            ->groupBy(DB::raw("date_format(created_at,'%Y-%m-%d')"));

        $list = DB::table('stock_change_record')
            ->select('orgz_id','product_id','stock_change_record.created_at','changed_inventory',
                DB::raw('date_format(stock_change_record.created_at,\'%Y-%m-%d\') as created_at_new'),
                DB::raw('CONCAT_WS(\'_\',orgz_id,product_id,date_format(stock_change_record.created_at,\'%Y-%m-%d\')) as op'))
            ->leftJoin(DB::raw("({$sub->toSql()}) as b"),'stock_change_record.created_at','=','b.created_at')
            ->addBinding($sub->getBindings())
            ->where('hq_code',$hq_code)
            ->whereIn('orgz_id',$orgz_ids)
            ->whereIn('product_id',$product_ids)
            ->whereBetween('stock_change_record.created_at',[$start_date,$end_date])
            ->orderBy('stock_change_record.id', 'desc')
            ->get();
        if(!empty($list)){
            $list = $list->toArray();
        }