0

我花了很多时间来寻找这个解决方案。我想导出用户选择的列数据列表,这是解决方案。解决方案是以数组形式获取列列表,然后将其转换为特定的数据库列名,然后将其传递给查询。laravel 的查询构造器接受数组。这让我的生活变得轻松,我想让你的生活变得轻松:)

问我有什么不清楚的。

 public function ExportData(Request $request)
    {
      $name = 'ArchiveData'.time();
      $headers = [
         'Cache-Control'       => 'must-revalidate, post-check=0, pre-check=0'
         ,   'Content-type'        => 'text/csv'
         ,   'Content-Disposition' => 'attachment; filename='.$name.'.csv'
         ,   'Expires'             => '0'
         ,   'Pragma'              => 'public'
     ];

     $column_title = array('a.a_sg' => 'Signature','a.a_sgo' => 'Signature old','p.p_title' => 'Portfolio','s.s_title' => 'Series','b.b_title' => 'Bundle','t.t_title' => 'Type','a.a_description' => 'Description','a.a_date_from' => 'Date From','a.a_date_to' => 'Date To','l.l_title' => 'Location','pe.pe_title' => 'Person','a.a_pr_note' => 'Private Note','ta.ta_title' => 'Tag');
     $ex_columns = array();
     foreach($column_title as $key => $value) {
      if(in_array($value,$request->exc)){

        $ex_columns[] = $key;
    }
}

$data =  DB::table('archive_data as a')
->join('person as pe', 'pe.pe_id', '=', 'a.a_pe_id')
->join('portfolio as p', 'p.p_id', '=', 'a.a_p_id')
->join('tag as ta', 'ta.ta_id', '=', 'a.a_ta_id')
->join('type as t', 't.t_id', '=', 'a.a_ty_id')
->join('location as l', 'l.l_id', '=', 'a.a_lc_id')
->join('series as s', 's.s_id', '=', 'a.a_s_id')
->join('bundle as b', 'b.b_id', '=', 'a.a_b_id')
->whereIn('a.a_id', $request->bk)
->select($ex_columns)
->get();   

                    // dd(DB::getQueryLog());

$data = json_decode(json_encode($data), true);

array_unshift($data, $request->exc);



$callback = function() use ($data) 
{
 $FH = fopen('php://output', 'w');
 foreach ($data as $row) { 
     fputcsv($FH, $row);
 }
 fclose($FH);
};

return Response::stream($callback, 200, $headers);
}
4

1 回答 1

2

您可以使用addSelect函数在系统编程方式中动态列。

根据您的解决方案替换以下行:-

$data =  DB::table('archive_data as a')
->join('person as pe', 'pe.pe_id', '=', 'a.a_pe_id')
->join('portfolio as p', 'p.p_id', '=', 'a.a_p_id')
->join('tag as ta', 'ta.ta_id', '=', 'a.a_ta_id')
->join('type as t', 't.t_id', '=', 'a.a_ty_id')
->join('location as l', 'l.l_id', '=', 'a.a_lc_id')
->join('series as s', 's.s_id', '=', 'a.a_s_id')
->join('bundle as b', 'b.b_id', '=', 'a.a_b_id')
->whereIn('a.a_id', $request->bk)
->select($ex_columns)
->get();   

进入

$dataQuery =  DB::table('archive_data as a')
->join('person as pe', 'pe.pe_id', '=', 'a.a_pe_id')
->join('portfolio as p', 'p.p_id', '=', 'a.a_p_id')
->join('tag as ta', 'ta.ta_id', '=', 'a.a_ta_id')
->join('type as t', 't.t_id', '=', 'a.a_ty_id')
->join('location as l', 'l.l_id', '=', 'a.a_lc_id')
->join('series as s', 's.s_id', '=', 'a.a_s_id')
->join('bundle as b', 'b.b_id', '=', 'a.a_b_id')
->whereIn('a.a_id', $request->bk);   

foreach($ex_columns as $ex_c){
$dataQuery = $dataQuery->addSelect($ex_c);
}

$data =  $dataQuery->get();
于 2020-04-23T02:45:32.707 回答