/**
*
*
* 订单数据导出
*/
public function export()
{
$where = [];
$total = Order::where($where)->count();
if ($total == 0) {
return '无数据';
}
$title = ['订单号', '商品名称', '规格', '数量','订单价格','创建时间', '订单状态','收货人姓名','电话','省份','市区','区域','地址'];
set_time_limit(0);
//设置程序运行内存
ini_set('memory_limit', '5M');
$fileName = '订单信息统计'.date('Y-m-d');
header('Content-Encoding: UTF-8');
header("Content-type:application/vnd.ms-excel;charset=UTF-8");
header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');
//打开文件
$fp = fopen('php://output', 'a');
//添加BOM头,以UTF8编码导出CSV文件,如果文件头未添加BOM头,打开会出现乱码。
fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
//数据写入csv文件
fputcsv($fp, $title);
$sqlLimit = 500;
// DB::enableQueryLog();
for($i = 0;$i < ceil($total/$sqlLimit);++$i){
$lists = Db::table('orders as a')
->leftJoin('address_users as b','a.address_id' ,'=' ,'b.id')
->leftJoin('product_skus as c','a.sku_id','=','c.id')
->leftJoin('product_spus as d','c.product_id','=','d.id')
->where($where)
->select('a.order_no','d.title','c.attrbute_text','a.num','a.amount','a.created_at','a.status','b.name','b.mobile','b.province','b.city','b.area','b.address')
->forPage($i,$sqlLimit)
->get()
->map(function ($value) {
$value->status = $this->orderStatus[$value->status];
return $value;
});
##yield引入
$lists = self::yieldData($lists);
foreach($lists as $r) {
//数据写入csv文件
$r->order_no = "\t".$r->order_no;
fputcsv($fp, (array)$r);
}
//数据从PHP的缓冲中释放出来
ob_flush();
// 被释放出来的数据发送到浏览器
flush();
}
/** * 第三步关闭文件流 */ ob_end_flush(); fclose($fp);
}
public static function yieldData($data)
{
foreach ($data as $datum){
yield $datum;
}
}
有话要说