php - 在 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);
}
任何的想法?
解决方案
解决了
我的一些数据core_id
列为空,这就是它无法正确导出数据的原因。
推荐阅读
- microsoft-teams - Ms Teams:如何知道安装了我的机器人的组织/公司名称
- css - CSS - 打字机动画,宽度等于内容
- php - OpenSSL 错误消息:错误:14095126 读取时出现意外 eof
- lilypond - 如何在五线谱上方显示和弦名称
- python - Python中二维数据的累积直方图
- c++ - a[0]=0 处的分段错误
- python - 我在 Dynamo-db 表中有一个 date_time 字段。如何仅查询两个特定时间日期之间的条目?
- assembly - ARM Thumb-2 PC 寄存器行为
- kubernetes - initcontainer 的限时执行
- python - 将多级列表中的“0”和“1”字符串转换为整数