1
我試圖使用maatwebsite使用Laravel Excel
package將對象中的多個項目導出到Laravel 5.1中的CSV中。Laravel從對象中導出多個項目
我正在使用的代碼工作,但只導出最後一條記錄,而不是所有記錄。
我的代碼是:
return Excel::create('Voucher-Export-'.time(), function($excel) use($rows)
{
$excel->setTitle('Voucher Export');
$excel->sheet('Voucher Export', function($sheet) use($rows) {
foreach($rows->items() as $row) {
$sheet->fromArray($row->toArray());
}
});
})->store('xls', false, true);
$rows
保持對象是這樣的:
array:20 [▼
0 => Coupon {#369 ▼
#table: "coupons"
#fillable: array:8 [▶]
#connection: null
#primaryKey: "id"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:12 [▶]
#original: array:12 [▶]
#relations: []
#hidden: []
#visible: []
#appends: []
#guarded: array:1 [▶]
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
+wasRecentlyCreated: false
}
1 => Coupon {#370 ▶}
2 => Coupon {#371 ▶}
3 => Coupon {#372 ▶}
4 => Coupon {#373 ▶}
5 => Coupon {#374 ▶}
6 => Coupon {#375 ▶}
7 => Coupon {#376 ▶}
8 => Coupon {#377 ▶}
9 => Coupon {#378 ▶}
10 => Coupon {#379 ▶}
11 => Coupon {#380 ▶}
12 => Coupon {#381 ▶}
13 => Coupon {#382 ▶}
14 => Coupon {#383 ▶}
15 => Coupon {#384 ▶}
16 => Coupon {#385 ▶}
17 => Coupon {#386 ▶}
18 => Coupon {#387 ▶}
19 => Coupon {#388 ▶}
]
然而,這導致只有最後一排被導出。有誰知道這可以做到嗎?
如果'$ rows'是一個數組,想必你的代碼應該是'的foreach($行作爲$行)'而不是'foreach($ rows-> items()as $ rows)''。但是,如果我假設你已經簡化了這種情況,你的'rows'變量實際上就是一個模型,而'-> items()'是某種關係方法 - 嘗試在沒有'()'的情況下調用它 - 'foreach($ user-> addresses as $ address)'而不是'foreach($ user-> addresses()as $ address)''。我並不是說這肯定會解決你的問題 - 只有最後一項很奇怪 - 但也許它會幫助你更仔細地審視你的代碼。 – alexrussell