Enloquent关系列的总和

Enloquent关系列的总和

本文介绍了Laravel Enloquent关系列的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在做一个购物车应用程序,现在我来到了以下问题。



有一个用户,一个产品和Cart对象。

- Cart表仅包含以下列:id,user_id,product_id和时间戳。

- UserModel haveManyCarts(因为用户可以存储多个产品)。

- CartModelbelongsTo一个用户和CartModelhasMany产品。



现在计算我可以调用的总产品: Auth :: user() - > cart() - > count 。我的问题是:如何获取该用户购物中的产品的价格(产品列)的SUM()?

我想通过雄辩而不是通过使用查询(主要是因为我相信它是一个很清洁)来完成这个。



-Thanx

解决方案

Auth :: user() - > products-> sum('price');



这些文档对于某些 Collection 方法来说有点光明,但是所有的查询生成器聚合似乎都是除了 avg()可以在。


Hi I've been working on a shoppingcart application and now I've come to the following issue..

There is a User, a Product and a Cart object.
- 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 CartModel "hasMany" Products.

Now to calculate the total products I can just call: Auth::user()->cart()->count().

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).

-Thanx

解决方案

Auth::user()->products->sum('price');

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 Enloquent关系列的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 01:56