所以我试图从所有账单中获取所有细节,在bill_details表中我有一个列来识别这个细节所属的账单(foreing key),我的查询看起来像这样:
return $this
->join('bill_detail as bd' , 'bills.id' , '=', 'bd.bill_id')
->join('business' , 'bills.business_id' , '=', 'business.id')
->select('bills.user_id','bd.item','bd.quantity','bd.amount','bd.bill_id','bills.total')
->where('bills.user_id', '=', $user)
->get();
返回此stclass或数组(使用php格式化):
array(4) {
[0]=> array(6)
{ ["user_id"]=> int(1) ["item"]=> string(4) "Coffe" ["quantity"]=> int(1) ["amount"]=> string(4) "2.00" ["bill_id"]=> int(1) ["total"]=> string(5) "15.00" }
[1]=> array(6)
{ ["user_id"]=> int(1) ["item"]=> string(18) "Water" ["quantity"]=> int(1) ["amount"]=> string(4) "6.00" ["bill_id"]=> int(1) ["total"]=> string(5) "15.00" }
[2]=> array(6)
{ ["user_id"]=> int(1) ["item"]=> string(7) "Apple" ["quantity"]=> int(1) ["amount"]=> string(4) "1.00" ["bill_id"]=> int(2) ["total"]=> string(5) "23.00" }
[3]=> array(6)
{ ["user_id"]=> int(1) ["item"]=> string(8) "Orange" ["quantity"]=> int(1) ["amount"]=> string(4) "4.00" ["bill_id"]=> int(2) ["total"]=> string(5) "23.00" }
}
是否有任何最佳方式而不是foreach将此数组拆分为基于bill_id列的多维数组?
感谢。
答案 0 :(得分:0)
是的,你可以collect
然后按bill_id
分组。
$results = $this
->join('bill_detail as bd' , 'bills.id' , '=', 'bd.bill_id')
->join('business' , 'bills.business_id' , '=', 'business.id')
->select('bills.user_id','bd.item','bd.quantity','bd.amount','bd.bill_id','bills.total')
->where('bills.user_id', '=', $user)
->get();
return collect($results)->groupBy('bill_id');