【问题标题】:Laravel Maatwebsite excel arrayLaravel Maatwebsite excel 数组
【发布时间】:2018-09-22 15:47:29
【问题描述】:

我是 Laravel 的新手,但我使用 laravel 的 Maatwebsite\Excel Library v3 来导出 excel。但是我在导出数组数据时遇到了一些问题。

这是我的代码

    <?php

namespace App\Exports;
use App\Team;

use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithHeadings;

class RegisteredMemberExport implements FromCollection, WithHeadings
{
    use Exportable;

    public function collection()
    {

     $data = Team::where('reg', 1)->get();       

        return collect([
            [
                'name' => $data->name,
                'email' => $data->email
            ]
        ]);
    }

    public function headings(): array
    {
        return [
            'name',
            'email'
        ];
    }

}

收集应该是

return collect
([
            [
                'name' => 'Povilas',
                'email' => 'povilas@laraveldaily.com'
            ],
            [
                'name' => 'Taylor',
                'email' => 'taylor@laravel.com'
            ]
        ]);

我不能在 collect 方法返回中使用循环。 我可以帮忙吗?

【问题讨论】:

  • 你想从coolection得到什么数据
  • 你想用循环做什么?

标签: php laravel


【解决方案1】:

您可以使用属性列表作为 get 方法的参数,直接从 Eloquent 模型中过滤您需要的值。

$data = Team::where('reg', 1)->get(['name', 'email']);

return collect($data->toArray());

【讨论】:

    【解决方案2】:

    您可以使用eachmap 或任何您想要的Laravel Collections 链方法,如下所示:

    return collect([
                     ['name' => 'Povilas','email'=>'povilas@laraveldaily.com'],
                     ['name' => 'Taylor','email' => 'taylor@laravel.com']
                  ])->each(function($value){
                     return $value; // Do what you want here
             }); 
    

    【讨论】:

      【解决方案3】:

      您可以使用与FromCollection 相同的Maatwebsite\Excel\Concerns\FromArray 关注点。

      <?php
      
      namespace App\Exports;
      
      use Maatwebsite\Excel\Concerns\FromArray;
      use Maatwebsite\Excel\Concerns\WithHeadings;
      
      class RegisteredMemberExport implements FromArray, WithHeadings
      {
          public function array(): array
          {
              return [
                  [
                      'name' => 'Povilas',
                      'email' => 'povilas@laraveldaily.com',
                  ],
                  [
                      'name' => 'Taylor',
                      'email' => 'taylor@laravel.com',
                  ],
              ];
          }
      
          public function headings(): array
          {
              return [
                  'name',
                  'email',
              ];
          }
      }
      

      Source

      【讨论】:

        猜你喜欢
        • 2017-11-12
        • 2021-09-17
        • 1970-01-01
        • 2019-05-20
        • 2019-01-28
        • 2016-12-16
        • 1970-01-01
        • 2021-05-26
        • 1970-01-01
        相关资源
        最近更新 更多