2013-11-09 183 views
0

我想知道我怎麼可以把事先準備好的聲明中laravel 4Laravel 4預處理語句

這是我準備的語句寫在MySQL工作臺:

SET @sql = NULL; 

SELECT 
    GROUP_CONCAT(DISTINCT 
    CONCAT(
     'MAX(IF(`payroll_item_id` = ', `payroll_item_id`, ', amount, NULL)) i', `payroll_item_id`) 
) INTO @sql 
FROM payroll_item_settings; 

SET @sql = CONCAT('SELECT employee_id, ', @sql, ' FROM payroll_item_settings GROUP BY employee_id'); 

PREPARE stmt FROM @sql; 
EXECUTE stmt; 
DEALLOCATE PREPARE stmt; 

回答

0

我發現了一個解決辦法,我這樣使用一個存儲過程:

DELIMITER $$ 

CREATE PROCEDURE employees_payroll_settings() 

BEGIN 

SET @sql = NULL; 

SELECT 
    GROUP_CONCAT(DISTINCT 
    CONCAT(
     'MAX(IF(`payroll_item_id` = ', `payroll_item_id`, ', amount, NULL)) AS `', payroll_items.payroll_item, '`') 
) INTO @sql 
FROM payroll_item_settings 
JOIN payroll_items 
ON payroll_items.id = payroll_item_settings.payroll_item_id; 

SET @sql = CONCAT('SELECT employees.employee_name, ', @sql, ' FROM payroll_item_settings JOIN employees ON employees.id = payroll_item_settings.employee_id GROUP BY employee_id'); 

PREPARE stmt FROM @sql; 
EXECUTE stmt; 
DEALLOCATE PREPARE stmt; 

END $$ 

DELIMITER ; 

然後在我的控制,我把這樣的事情:

$payroll_items = DB::table('payroll_items') 
       ->distinct() 
       ->join('payroll_item_settings', 'payroll_items.id', '=', 'payroll_item_settings.payroll_item_id') 
       ->select('payroll_items.*', 'payroll_item_settings.payroll_item_id') 
       ->get(); 
     $payroll_item_settings = DB::select('CALL employees_payroll_settings()'); 
     return View::make('payroll_item_setting.index', array(
        'payroll_item_settings' => $payroll_item_settings, 
        'payroll_items' => $payroll_items 
     ));