【问题标题】:Mapping export data in Laravel在 Laravel 中映射导出数据
【发布时间】:2020-09-25 09:02:36
【问题描述】:

我有使用laravel excel 的导出功能。目前我的数据正在导出,但我想将相关的表数据添加到我的 csv 中,而不仅仅是 id。

样本

这是我目前得到的

id-name-core_id-created_at-updated_at

我想得到什么

id-name-core_name-created_at-updated_at

对于这个问题,我发现映射 (source) 可能是解决方案,但它会导出空白 csv。

代码

Export class

<?php

namespace App\Exports;

use App\CableAlokasi;
use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\Concerns\FromCollection;
use Illuminate\Contracts\Support\Responsable;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\Exportable;

// added
use Maatwebsite\Excel\Concerns\WithMapping;

class CableAlokasiExport implements WithMapping
{
    use Exportable;

    private $fileName = 'Alokasies.csv';

    /**
    * Optional Writer Type
    */
    private $writerType = Excel::CSV;

    /**
    * Optional headers
    */
    private $headers = [
        'Content-Type' => 'text/csv',
    ];


    // added for mapping data
    public function map($alokasi): array
    {
        return [
            $alokasi->id,
            $alokasi->core->name,
            $alokasi->name,
            $alokasi->created_at,
            $alokasi->updated_at,
        ];
    }
    //

    public function headings(): array
    {
        return [
            '#',
            'core',
            'name',
            'created_at',
            'updated_at',
        ];
    }

    public function collection()
    {
        return CableAlokasi::all();
    }
}

Controller

public function export(Request $request) 
{
    $filename = Carbon::now()->format('Ymdhms').'-Alokasies.xlsx';
    Excel::store(new CableAlokasiExport, $filename);
    $fullPath = url('exports', $filename);

    return response()->json([
        'data' => $fullPath,
        'message' => 'Alokasies are successfully exported.'
    ], 200);
}

有什么想法吗?

【问题讨论】:

  • 你检查错误日志了吗?
  • @ShafeequeTP 我没有收到错误我的导出文件开始下载没有问题,只是为空
  • 可能有一些警告可以帮助您识别问题
  • @ShafeequeTP message: "Trying to get property 'name' of non-object"
  • @ShafeequeTP 我也找到了this 并更改了我的收集功能结果是同样的错误

标签: php laravel


【解决方案1】:

已解决

我的一些数据core_id 列为空,这就是它无法正确导出数据的原因。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-14
    • 2021-04-20
    • 1970-01-01
    • 2014-03-15
    • 2017-12-02
    • 2014-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多