C
C
chelkaz2017-05-09 10:16:13
MySQL
chelkaz, 2017-05-09 10:16:13

MySql Is it possible to get SUM() for several fields with one query?

I do not need a common for two fields, but a different result for two fields! Now I can only do this: First, I pull out everything related by the point
field , since it determines whether it belongs to the product card, and then I work with the received object ... In the example, queries through the framework class, but if you know how to make a query through SQL, then write.

$ratings = DB::table('ratings')->where('point', 'test');
// Выбираю одно
$avg_ecology = $ratings->sum('ecology');
// Потом другое
$avg_social_protection = $ratings->sum('social_protection');

Can't you make a request to return an array? For example:
DB::table('ratings')->where('point', 'test')->sum('ecology')->sum('social_protection');

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
pantagruel964, 2017-05-09
@pantagruel964

$ratings = DB::table('ratings')
                 ->selectSub(function ($query) {
                     return $query->selectRaw('SUM(ecology)');
                 }, 'ecology')
                 ->selectSub(function ($query) {
                     return $query->selectRaw('SUM(social_protection)');
                 }, 'social_protection')
                 ->where('point', 'test')
                 ->get();

U
UksusoFF, 2017-05-09
@UksusoFF

You can try playing around with DB::raw()
And yet you seem to be working with collections, not MySQL.
https://laravel.com/docs/5.4/collections#method-sum
https://laravel.com/docs/5.4/queries
And if you need to count the number of related models, then you need to use https://laravel.com/ docs/5.4/eloquent-relationship...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question