我找到了一种解决方法,我使用了这样的存储过程:
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
));