php Laravel.从数据库问题中导出结果

rryofs0p  于 2022-10-30  发布在  PHP
关注(0)|答案(1)|浏览(129)

尽可能短。我的代码运行通过多个数据库计数对象和匹配名称-对象的数量它像一个脚本(命令在laravel),导出结果在.csv文件运行。

$formatted_data = array();
        $providers = provider::where('del', 'no')->get();       
        foreach($providers as $provider){   
            $formatted_data[$provider['id']]['name'] = $provider['name'];
        }

        $objectMappingsModels = array((new objectMapping1), (new objectMapping2),
         (new objectMapping3), (new objectMapping4), (new objectMapping5),
         (new objectMapping6), (new objectMapping7), (new objectMapping8));

         foreach($objectMappingsModels as $objectMappingsModel){
            $totals = $objectMappingsModel::select('providerFK', DB::raw('count(*) as total'), 
                                                                 DB::raw('monthName(ut) as month_name')
                                                  )
                                          ->where('userFK', '!=', 1)  
                                          ->where('del', 'no')
                                          ->whereMonth('ut', $this->option('month'))   
                                          ->whereYear('ut', $this->option('year'))
                                          ->groupBy('providerFK', 'month_name')
                                          ->get()
                                          ->toArray();              

            foreach($totals as $total){
                $formatted_data[$total['providerFK']]['count'] = $total['total'];
            }   

        }
        $responce =  Excel::store(new UsersExport($formatted_data), 'testNameDate.csv',null, \Maatwebsite\Excel\Excel::CSV);
        return true;

这就是我的代码。

class UsersExport implements FromArray
{
    protected $invoices;

    public function __construct(array $invoices)
    {
        $this->invoices = $invoices;
    }

    public function array(): array
    {
        return $this->invoices;
    }
}

这就是我的出口课程。
不幸的是,它并不是完美的工作。它不时地给我错误的结果。有些记录是正确的,有些是错误的。而且,最后一行总是只有一个随机数(没有名称附加到它)。你知道为什么会出现这样的问题吗?你能给我一些代码优化建议吗?
谢谢你!

xjreopfe

xjreopfe1#

我在最后一个循环中添加了这个if-else

if(isset($formatted_data[$total['providerFK']]['count'])){
                    $formatted_data[$total['providerFK']]['count'] += $total['total'];
                }else{
                    $formatted_data[$total['providerFK']]['count'] = $total['total'];
                }

它似乎解决了一些问题

相关问题