Laravel - объединяет несколько запросов в один, а также включает GroupBy - PullRequest
0 голосов
/ 02 июля 2019

Я написал разные запросы, которые работают для разных вещей. Я хочу объединить их в одно (Продажи за: Сегодня, Текущая неделя, Текущая неделя, Текущий месяц, Текущий год и Общие продажи) и Группировать по полю с именем store.

            $currentYear = date('y');
        $currentyearbilling = DB::table("billings")
               ->select(DB::raw("SUM(amount) as total"))
               ->whereRaw('YEAR(created_at) = ?',$currentYear)
               ->get();

        $currentMonth = date('m');
        $currentmonthbilling = DB::table("billings")
               ->select(DB::raw("SUM(amount) as total"))
               ->whereRaw('MONTH(created_at) = ?',$currentMonth)
               ->get();

        $currentWeek = date('w');
        $currentweekbilling = DB::table("billings")
               ->select(DB::raw("SUM(amount) as total"))
               ->whereRaw('WEEK(created_at) = ?',$currentWeek)
               ->get();

        $currentDay = date('d');
        $currentdaybilling = DB::table("billings")
               ->select(DB::raw("SUM(amount) as total"))
               ->whereRaw('(created_at) = ?',$currentDay)
               ->get(); 

Группа По магазину.

Имя таблицы называется биллингом. Я все еще хочу следовать этому формату

DB :: таблица ( "Биллингс") Как мне этого добиться?

syntax error

Ошибка:

Ответы [ 2 ]

0 голосов
/ 02 июля 2019

Допустим, у нас есть таблица billings, например:

| column     | type       |
|------------|------------|
| id         | int        |
| store      | varchar    |
| amount     | int        |
| created_at | timestamps |
| updated_at | timestamps |

Я получу количество каждого магазина в current_day, current_month, current_week, current_year и overall с помощью подзапроса, подобного этому:

select 
  store,
  (SELECT SUM(amount) from billings as child where child.store = parent.store and DAY(created_at) = ? and MONTH(created_at) = ? and YEAR(created_at) = ?) as current_day,
  (SELECT SUM(amount) from billings as child where child.store = parent.store and WEEK(created_at) = ?) as current_week,
  (SELECT SUM(amount) from billings as child where child.store = parent.store and MONTH(created_at) = ? and YEAR(created_at) = ?) as current_month,
  (SELECT SUM(amount) from billings as child where child.store = parent.store and YEAR(created_at) = ?) as current_year,
  SUM(amount) as overall,
  COUNT(id) as total_rows

from billings as parent

group by store

А с Eloquent это будет примерно так:

$childQuery = \DB::table(\DB::raw('billings as child'))
    ->select(\DB::raw('SUM(amount) as amount'))
    ->whereRaw('child.store = parent.store');

$currentDayQuery = (clone $childQuery)->whereDay('created_at', now()->day)->whereMonth('created_at', now()->month)->whereYear('created_at', now()->year);
$currentWeekQuery = (clone $childQuery)->where(\DB::raw('WEEK(created_at)'), now()->weekOfYear);
$currentMonthQuery = (clone $childQuery)->whereMonth('created_at', now()->month);
$currentYearQuery = (clone $childQuery)->whereYear('created_at', now()->year);

$rows = \DB::table(\DB::raw('billings as parent'))
    ->select([
        'store',
        \DB::raw('(' . $currentDayQuery->toSql() . ') as current_day'),
        \DB::raw('(' . $currentWeekQuery->toSql() . ') as current_week'),
        \DB::raw('(' . $currentMonthQuery->toSql() . ') as current_month'),
        \DB::raw('(' . $currentYearQuery->toSql() . ') as current_year'),
        \DB::raw('SUM(amount) as overall'),
        \DB::raw('COUNT(id) as total_rows')
    ])
    ->mergeBindings($currentDayQuery)
    ->mergeBindings($currentWeekQuery)
    ->mergeBindings($currentMonthQuery)
    ->mergeBindings($currentYearQuery)
    ->groupBy('store')
    ->get();

Надеюсь, это поможет.

0 голосов
/ 02 июля 2019

Вы должны попробовать это:

$currentYear = date('y');
$currentMonth = date('m');
$currentWeek = date('w');
$currentDay = date('d');

$currentyearbilling = DB::table("billings")
       ->select(DB::raw("SUM(amount) as total"))
       ->whereRaw('YEAR(created_at) = ?',$currentYear)
       ->orWhereRaw('MONTH(created_at) = ?',$currentMonth)
       ->orWhereRaw('WEEK(created_at) = ?',$currentWeek)
       ->orWhereRaw('(created_at) = ?',$currentDay)
       ->groupBy('store')
       ->get();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...