首页 > 解决方案 > 在 Laravel 中映射导出数据

问题描述

我有使用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);
}

任何的想法?

标签: phplaravel

解决方案


解决了

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


推荐阅读