生成具有多对多关系的PHPExcel Laravel Excel

时间:2017-08-03 14:44:18

标签: php laravel-5 phpoffice

我正在开设一个考试/测验应用程序,它会为用户创建测试/测验,现在我必须创建一组电子表格,其中包含给定考试中的当前学生,等级图表等数据。

到目前为止,我设法创建的是一张包含所有用户使用` - > fromModel'但如果我使用任何关系和/或约束我得到一张空白纸。

我有这个型号:

 <?php

namespace EMMA5;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Exam extends Model
{
    //

    protected $dates = ['created_at', 'updated_at', 'applicated_at'];

    protected $fillable = [
        'applicated_at',
        'duration',
        'board_id',
        'passing_grade',
        'annotation'
   ];

    public function board()
    {
        return $this->belongsTo('EMMA5\Board');
    }

    public function users()
    {
        return $this->belongsToMany('EMMA5\User')->withPivot('active', 'started_at', 'ended_at', 'seat', 'location_id');
    }

... 用户模型(缩写)     class User扩展了Authenticatable     {     ...      //关系         公共功能答案()         {             return $ this-&gt; hasMany(Answer :: class);         }

    public function exams()
    {
        return $this->belongsToMany('EMMA5\Exam')->withPivot('active', 'started_at', 'ended_at', 'location_id');
    }

...

我正在尝试为特定考试的用户创建一个工作表: (这是来自我的ExamController.php)

/**
     * Returns a spreadsheet with only the students that were present
     *
     * @return PHPOffice
     */
    public function gradesSpreadshet(Exam $exam)
    {
            $grade = new Grade;
            $gradedStudents = $grade->allStudents($exam)->toArray();
            //dd(\EMMA5\Exam::find(195)->with('users')->get());
            //dd($exam->answers->answer);
            $data = $exam->users;
            return Excel::create("FinalGrades", function ($excel) use($data) {
                    //Create sheet to be able to return something to keep on testing

                    //Another sheet
                    $excel->sheet('Primera hoja', function ($sheet) use($data) {
                            $sheet->fromArray($data);
                    });
            })->export('xlsx');
    }

我得到一张空白纸。 我已尝试使用->fromArray()->fromModel()。 将欣赏任何意见。

1 个答案:

答案 0 :(得分:0)

一段时间过去了,没有人回答,但我找到了解决方案。 我不知道这对其他人是否有帮助。

Excel Laravel无法读取结果的方式。所以我用回调函数创建了一个辅助函数。

public static function collectionToArray(Array $collect = null) { return array_map(function ($array) use($collect) { foreach ($array as $key => $value) { $resultArray[$key] = $value; } return $resultArray; }, $collect); } 这将返回Collection的简化版本,Excel Laravel可以轻松读取。