eloquent - 在 Laravel 中将数据导出到 Excel 文件时使用 Eloquent 关系

标签 eloquent laravel-5.1 maatwebsite-excel

我想为我的两个表创建一个汇总报告,一个是员工表,另一个是 sims 表。这些表具有一对多的关系。我知道我们可以通过使用导出模型的数据->fromModel($model)但是有没有办法让我可以根据这两个表生成报告?

最佳答案

所以,我问了一个问题,一个无法回答但胆怯地授予-1的人。但是,我想出了如何手动执行此操作。发布代码以便它可以帮助像我这样的 future 初学者。

public function downloadSummary(){

        Excel::create('records', function($excel) {

            $excel->sheet('Sheet1', function($sheet) {
                $employees = Employee::all();

                $arr =array();
                foreach($employees as $employee) {
                    foreach($employee->sims as $sim){
                        $data =  array($employee->id, $employee->name, $employee->nic, $employee->address, $employee->title,
                            $sim->id, $sim->msisdn, $sim->imei, $sim->issued_to);
                        array_push($arr, $data);
                    }
                }

                //set the titles
                $sheet->fromArray($arr,null,'A1',false,false)->prependRow(array(
                        'Employee Id', 'Employee Name', 'Employee NIC', 'Employee Address', 'Employee Title',
                        'Sim Id', 'Sim MSISDN', 'IMEI', 'Issued To'
                    )

                );

            });

        })->export('xls');
    }

关于eloquent - 在 Laravel 中将数据导出到 Excel 文件时使用 Eloquent 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33485408/

相关文章:

php - 使用 Excel::import 在 Maatwebsite/Laravel Excel 3.1 上导入 CSV

php - 向 Laravel 5 调度程序添加自定义方法

php - 我如何使用 laravel 获得多个计数查询?

laravel - 如何在 Eloquent 数据透视表上设置额外字段的值

php - laravel eloquent 在 varchar 中写入新行

linux - 通过composer安装laravel 5.1 SSL3证书错误

mysql - 在 laravel 中使用 maatwebsite excel 上传之前检查导入文件

laravel-5 - Laravel Excel - 选择要导出的列

php - 如何从每个父模型的模型中获取 N 条记录?在 Laravel Eloquent 中

php - SQL记录检索