【问题标题】:Generate PHPExcel Laravel Excel with many to many relations生成具有多对多关系的 PHPExcel Laravel Excel
【发布时间】:2018-01-11 06:07:11
【问题描述】:

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

到目前为止,我设法创建的只是一张所有用户都使用 `->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');
    }

... 用户模型(缩写) 类用户扩展可验证 { ... //关系 公共功能答案() { 返回 $this->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');
    }

我得到了一张空纸。 我已经尝试过 -&gt;fromArray()-&gt;fromModel() 。 将不胜感激任何意见。

【问题讨论】:

    标签: php laravel-5 phpoffice


    【解决方案1】:

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

    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); } 这将返回一个可以被 Excel Laravel 轻松读取的 Collection 的简化版本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-14
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多