問題描述
我一直在開發一個購物車應用程序,現在我遇到了以下問題..
I've been working on a shopping cart application and now I've come to the following issue..
有一個用戶、一個產品和一個購物車對象.
- 購物車表僅包含以下列:
id
、user_id
、product_id
和時間戳. - UserModel
hasMany
Carts(因為一個用戶可以存儲多個產品). - CartModel
belongsTo
用戶和 CartModelhasMany
產品.
- The Cart table only contains the following columns:
id
,user_id
,product_id
and timestamps. - The UserModel
hasMany
Carts (because a user can store multiple products). - The CartModel
belongsTo
a User and CartModelhasMany
Products.
現在計算我可以調用的總產品數:Auth::user()->cart()->count()
.
Now to calculate the total products I can just call: Auth::user()->cart()->count()
.
我的問題是:如何獲得該用戶購物車中產品的價格(一列產品)的SUM()
?
我想使用 Eloquent 而不是使用查詢來完成此操作(主要是因為我認為它更簡潔).
My question is: How can I get the SUM()
of prices (a column of product) of the products in cart by this User?
I would like to accomplish this with Eloquent and not by using a query (mainly because I believe it is a lot cleaner).
推薦答案
Auth::user()->products->sum('price');
文檔對某些 Collection
方法略顯簡單,但除了 avg()
之外,所有查詢構建器聚合似乎都可用,可在 http://laravel.com/docs/queries#aggregates.
The documentation is a little light for some of the Collection
methods but all the query builder aggregates are seemingly available besides avg()
that can be found at http://laravel.com/docs/queries#aggregates.
這篇關于Laravel Eloquent Sum of關系的列的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!