2017-07-13 16 views
0

我試圖通過連接三個表使Laravel中的Excel工作表在Excel工作表中輸出查詢的結果。class stdClass的對象無法轉換爲Excel表格中的Laravel字符串下載

型號檢索查詢結果:

<?php 
namespace App; 
use Illuminate\Support\Facades\DB; 
use Illuminate\Database\Eloquent\Model; 

class Product extends Model { 
    protected $table= 'product_master'; 
    protected $primaryKey = 'product_id'; 

    public static function download() { 
     $data=DB::table('product_master') 
      ->join('subcategory_master', 'product_master.subcategory_id', '=', 'subcategory_master.id') 
      ->join('category_master', 'product_master.category_id', '=', 'category_master.id') 
      ->select('product_master.product_id','product_master.product_name','product_master.part_number','category_master.category_name','subcategory_master.subcategory_name','product_master.net_quandity','gross_weight','product_master.product_type','product_master.description') 
      ->where('delete_status','=','0')->get(); 
     return($data); 
    } 
} 

控制器:

<?php 
namespace App\Http\Controllers; 

use Illuminate\Http\Request; 
use App\Http\Controllers\Controller; 
use App\Product; 
use Excel; 

class ExcelController extends Controller { 
    public function downloadExcel(Request $request, $type) { 
     $data = Product::download()->all(); 

     return Excel::create('productmaster', function($excel) use ($data) { 
      $excel->sheet('mySheet', function($sheet) use ($data) { 
       $sheet->fromarray($data); 
      }); 
     })->download($type); 
    } 
} 

路線:

Route::get('downloadExcel/{type}', '[email protected]'); 
+0

究竟是在哪裏發生的錯誤? – Kai

+0

$ sheet-> fromArray($ data);在控制器 –

回答

0

我的猜測是,您的查詢結果是包含產品對象的數組。對象是關鍵 - >值。但Excel工具預計只有價值。

您的查詢結果:

[['id'=>12, 'name'=>'Fidget Spinner'], ['id'=>13, 'name'=>'Shampoo'], ...] 

它應該是什麼:

[[12,'Fidget Spinner'], [13, 'Shampoo'], ...] 

試着這樣做:

$data= Product::download()->all(); 
foreach($data as $k => $v){ 
    $data[$k] = array_values($v->getAttributes()); 
} 
+0

當我嘗試此代碼它產生以下內容:FatalErrorException 調用未定義的方法stdClass :: getAttributes() –

+0

感謝很多凱-----我改變了代碼:::::'公共功能downloadExcel (請求$請求,$型) \t { \t \t \t $ \t數據=產品::下載() - >所有(); \t \t foreach($ data as $ k => $ v){ \t \t \t $ v =(array)$ v; \t \t \t $ data [$ k] =(array_values($ v)); \t \t}' \t這個作品非常感謝你爲你推動成功 –

相關問題