我在Laravel 5.4中拥有一个几乎完整的系统,但是我很难在集合的键上使用sum。
我在论坛中尝试了一系列自己的代码片段,还尝试了各种误导性代码(根据我的经验)。
这是收藏集:
Collection {#263 ▼
#items: array:3 [▼
5 => Collection {#224 ▼
#items: array:10 [▼
0 => {#213 ▼
+"id": 1
+"portfolio_id": 5
+"type": "Secured Note"
+"date": "2018-11-18"
+"inv_amount": "300000"
+"return_rate": "10%"
+"payment_amount": "7500"
+"inv_term": "18 Months"
+"payment_schedule": "Monthly"
+"account_info": "US BANK 4532"
+"pdffiles": null
+"created_at": "2019-04-19 01:51:53"
+"updated_at": "2019-04-19 11:53:03"
+"user_id": 1
+"hide": null
+"contract": null
+"reports": null
+"taxdocs": null
}
1 => {#252 ▶}
2 => {#253 ▶}
3 => {#254 ▶}
4 => {#255 ▶}
5 => {#256 ▶}
6 => {#257 ▶}
7 => {#258 ▶}
8 => {#259 ▶}
9 => {#260 ▶}
]
}
6 => Collection {#261 ▼
#items: array:1 [▼
0 => {#218 ▼
+"id": 2
+"portfolio_id": 6
+"type": "Secured Note"
+"date": "2018-09-15"
+"inv_amount": "350000"
+"return_rate": "12%"
+"payment_amount": "7500"
+"inv_term": "24 Months"
+"payment_schedule": "Monthly"
+"account_info": "US BANK 4532"
+"pdffiles": null
+"created_at": "2019-04-19 01:53:46"
+"updated_at": "2019-04-19 03:14:03"
+"user_id": 1
+"hide": null
+"contract": null
+"reports": null
+"taxdocs": null
}
]
}
7 => Collection {#262 ▼
#items: array:1 [▼
0 => {#238 ▼
+"id": 3
+"portfolio_id": 7
+"type": "Secured Note"
+"date": "2018-06-11"
+"inv_amount": "380000"
+"return_rate": "15%"
+"payment_amount": "8900"
+"inv_term": "36 Months"
+"payment_schedule": "Monthly"
+"account_info": "US BANK 4532"
+"pdffiles": null
+"created_at": "2019-04-19 01:54:45"
+"updated_at": "2019-04-24 00:38:21"
+"user_id": 1
+"hide": null
+"contract": null
+"reports": null
+"taxdocs": null
}
]
}
]
这是在控制器中生成它的原因:
$grouped = DB::table('funds')
->get()
->groupBy('portfolio_id');
dd($grouped);
基金模型属于投资组合,投资组合模型有很多基金。
从收藏集中,我有3个投资组合。我正在尝试从groupBy生成的3个付款中的每个付款的总和。
帮助!
答案 0 :(得分:0)
您应在groupBy()
之前使用get()
。另外,您还需要在选择项上使用SUM。
$grouped = DB::table('funds')
->select(DB::raw("portfolio_id, SUM(payment_amount)"))
->groupBy('portfolio_id')
->get();
dd($grouped);