我發現了一個解決辦法,我這樣使用一個存儲過程:
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
));