laravel - 使用 Maatwebsite/Laravel-Excel 生成 csv 文件如何使标题返回动态数组
问题描述
在 laravel 5.8 生成 csv 文件中,我使用 https://github.com/Maatwebsite/Laravel-Excel 插件,它工作正常,但是因为我使用标题方法生成标题 https://docs.laravel-excel.com/3.1/出口/mapping.html
我需要根据从 db 获得的结果集来设置标题:
<?php
namespace App\Exports;
use Auth;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
class exportSearchResults implements FromCollection, WithHeadings
{
public function collection()
{
$searchResultRows = SearchResult
::getByUserList($this->user_list_id)
->select( 'source_id' )
->groupBy( 'source_id' )
->orderBy('source_id', 'asc')
->get()
->toArray();
...
return $searchResultRows;
}
public function headings(): array
{
return [
'field',
'value',
];
// I need Somehow to return content of this array based on $searchResultRows array in collection method
}
}
有没有这样的方法?
解决方案
你可以使用这样的东西:
<?php
namespace App\Exports;
use Auth;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
class exportSearchResults implements FromCollection, WithHeadings
{
private $searchResultRows;
public function collection()
{
return $this->searchResultRows;
}
public function headings(): array {
$this->searchResultRows = SearchResult::getByUserList($this->user_list_id)
->select( 'source_id' )
->groupBy( 'source_id' )
->orderBy('source_id', 'asc')
->get()
->toArray();
...
if ($this->searchResultRows ...){
return [
'field',
'value',
];
} else {
return ...
}
}
}
推荐阅读
- playwright - 我们如何以角度发布和订阅剧作家中的事件?
- spring - PreparedStatementCallback; 无法转换类
由于 com.mysql.cj.exceptions.WrongArgumentException 请求的 SQL 类型 - api - 拆分不适用于翻译的对象
- python - 为单元测试禁用/修补 flask_of_oil OAuthFilter 装饰器
- c# - NetworkStream 在 Unity 中接收到一个空字符串数据
- c# - 订购系统应该如何工作。网页接口
- mod-rewrite - 无法使用 apache http 服务器中 Location 标记中的上下文路径删除 url 中的空参数
- c++ - websocat 是否正确处理与 websocketpp 服务器的关闭握手?
- vaadin - Vaadin 14 - 错误:检测到从 DOM 中删除的容器元素
- azure-devops - 如何在 azure devops 管道中应用 terraform.tfvars