像这样的MySQL查询:
SELECT GROUP_CONCAT(DISTINCT CONCAT( 'ifnull(SUM(case when location_code = ''', location_code , ''' then quantity end),0) AS `', location_code , '`' ) ) INTO @sql FROM item_details; SET @sql = CONCAT('SELECT item_number,SUM(quantity) as "total_quantity", ', @sql, ' FROM item_details GROUP BY item_number'); PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
我想将其转换为雄辩的laravel,但我很困惑。因为存在很多陈述。存在PREPARE,EXECUTE,SET,DEALLOCATE等你可以看到上面的查询
PREPARE
EXECUTE
SET
DEALLOCATE
如何将其转换为雄辩的laravel?
主要是原始查询:
DB::table('item_details')->selectRaw('GROUP_CONCAT(...) INTO @sql')->get(); DB::statement('SET @sql = CONCAT(...)'); DB::statement('PREPARE stmt FROM @sql'); DB::statement('EXECUTE stmt'); DB::statement('DEALLOCATE PREPARE stmt');
尝试这个:
DB::table('item_details')->selectRaw('GROUP_CONCAT(...) INTO @sql')->get(); $sql = DB::selectOne('select @sql')->{'@sql'}; ItemDetails::select('item_number', DB::raw('SUM(quantity) as total_quantity')) ->selectRaw($sql) ->groupBy('item_number') ->get();