Laravel использование mysql индексация - PullRequest
0 голосов
/ 01 февраля 2020

У меня есть этот плохой код (извините), который использует слишком много из MySQL запросов, извините, что он слишком длинный

    return view('dashboard.homepage', array(
            'DriversNumberApproved'      => \App\Models\Drivers::where('is_approved', 1)->count(),
            'DriversNumberUNApproved'      => \App\Models\Drivers::where('is_approved', 0)->count(),
            'DriversOnline'      => \App\Models\Drivers::where('is_active', 1)->count(),
            'DriversOnlineShow'      => \App\Models\Drivers::where('is_active', 1)->paginate(5)->appends(request()->query()),
            'DriversOffline'      => \App\Models\Drivers::where('is_active', 0)->where('is_approved', 1)->count(),
            'TodayMoneyTotal'      => \App\Models\Request::where('is_completed', 1)
                ->whereMonth('request_start_time', now()->month)
                ->whereDay('request_start_time', now()->day)
                ->whereYear('request_start_time', now()->year)->sum('total'),
            'TodayMoneyTotalP'      => \App\Models\Request::where('is_completed', 1)
                ->whereMonth('request_start_time', now()->month)
                ->whereDay('request_start_time', now()->day)
                ->whereYear('request_start_time', now()->year)->sum('total') / 5000 * 100,

            //This Week
            'TodayMoneyTotalWeek'      => \App\Models\Request::where('is_completed', 1)->whereBetween('request_start_time', 
                    [Carbon::now()->startOfWeek(), Carbon::now()])->sum('total'),
            'TodayMoneyTotalWeekP'      => \App\Models\Request::where('is_completed', 1)->whereBetween('request_start_time', 
                    [Carbon::now()->startOfWeek(), Carbon::now()])->sum('total') / 5000 * 100,


            //This Month
            'TodayMoneyTotalMonth'      => \App\Models\Request::where('is_completed', 1)->whereBetween('request_start_time', 
                    [Carbon::now()->startOfMonth(), Carbon::now()
                    ->endOfMonth()])->sum('total'),
            'TodayMoneyTotalMonthP'      => \App\Models\Request::where('is_completed', 1)->whereBetween('request_start_time', 
                    [Carbon::now()->startOfMonth(), Carbon::now()
                    ->endOfMonth()])->sum('total') / 5000 * 100,

//            Last 30 days
//            'TodayMoneyTotal30Last'      => \App\Models\Request::where('is_completed', 1)->whereDate('request_start_time', '=', Carbon::now()->subMonth()->month)->sum('total'),
//            'TodayMoneyTotal30LastP'      => \App\Models\Request::where('is_completed', 1)->whereDate('request_start_time', '=', Carbon::now()->subMonth()->month)->sum('total') / 5000 * 100,


            'TodayTripsTotal'      => \App\Models\Request::where('is_completed', 1)
                ->whereMonth('request_start_time', now()->month)
                ->whereDay('request_start_time', now()->day)
                ->whereYear('request_start_time', now()->year)->count(),
            'TodayTripsTotalP'      => \App\Models\Request::where('is_completed', 1)
                ->whereMonth('request_start_time', now()->month)
                ->whereDay('request_start_time', now()->day)
                ->whereYear('request_start_time', now()->year)->count() / 100 * 100,


            //This Week
            'TodayTripsTotalWeek'      => \App\Models\Request::where('is_completed', 1)->whereBetween('request_start_time', 
                    [Carbon::now()->startOfWeek(), Carbon::now()])->count(),
            'TodayTripsTotalWeekP'      => \App\Models\Request::where('is_completed', 1)->whereBetween('request_start_time', 
                    [Carbon::now()->startOfWeek(), Carbon::now()])->count() / 100 * 100,



            //This Month
            'TodayTripsTotalMonth'      => \App\Models\Request::where('is_completed', 1)->whereBetween('request_start_time', 
                    [Carbon::now()->startOfMonth(), Carbon::now()
                    ->endOfMonth()])->count(),
            'TodayTripsTotalMonthP'      => \App\Models\Request::where('is_completed', 1)->whereBetween('request_start_time', 
                    [Carbon::now()->startOfMonth(), Carbon::now()
                    ->endOfMonth()])->count() / 100 * 100,




            'TodayDistanceTotal'      => \App\Models\Request::where('is_completed', 1)
                ->whereMonth('request_start_time', now()->month)
                ->whereDay('request_start_time', now()->day)
                ->whereYear('request_start_time', now()->year)->sum('distance'),
            'TodayDistanceTotalP'      => \App\Models\Request::where('is_completed', 1)
                ->whereMonth('request_start_time', now()->month)
                ->whereDay('request_start_time', now()->day)
                ->whereYear('request_start_time', now()->year)->sum('distance') / 500 * 100,


            //This week
            'TodayDistanceWeekTotal'      => \App\Models\Request::where('is_completed', 1)->whereBetween('request_start_time', 
                    [Carbon::now()->startOfWeek(), Carbon::now()])->sum('distance'),
            'TodayDistanceWeekTotalP'      => \App\Models\Request::where('is_completed', 1)->whereBetween('request_start_time', 
                    [Carbon::now()->startOfWeek(), Carbon::now()])->sum('distance') / 500 * 100,





            //This Month
            'TodayDistanceMonthTotal'      => \App\Models\Request::where('is_completed', 1)->whereBetween('request_start_time', 
                    [Carbon::now()->startOfMonth(), Carbon::now()
                    ->endOfMonth()])->sum('distance'),
            'TodayDistanceMonthTotalP'      => \App\Models\Request::where('is_completed', 1)->whereBetween('request_start_time', 
                    [Carbon::now()->startOfMonth(), Carbon::now()
                    ->endOfMonth()])->sum('distance') / 500 * 100,






            'TodayTimeTotal'      => \App\Models\Request::where('is_completed', 1)
                ->whereMonth('request_start_time', now()->month)
                ->whereDay('request_start_time', now()->day)
                ->whereYear('request_start_time', now()->year)->sum('time'),
            'TodayTimeTotalP'      => \App\Models\Request::where('is_completed', 1)
                ->whereMonth('request_start_time', now()->month)
                ->whereDay('request_start_time', now()->day)
                ->whereYear('request_start_time', now()->year)->sum('time') / 5000 * 100,


            //This Week
            'TodayTimeWeekTotal'      => \App\Models\Request::where('is_completed', 1)->whereBetween('request_start_time', 
                    [Carbon::now()->startOfWeek(), Carbon::now()])->sum('time'),
            'TodayTimeWeekTotalP'      => \App\Models\Request::where('is_completed', 1)->whereBetween('request_start_time', 
                    [Carbon::now()->startOfWeek(), Carbon::now()])->sum('time') / 5000 * 100,




            //This Month
            'TodayTimeMonthTotal'      => \App\Models\Request::where('is_completed', 1)->whereBetween('request_start_time', 
                    [Carbon::now()->startOfMonth(), Carbon::now()
                    ->endOfMonth()])->sum('time'),
            'TodayTimeMonthTotalP'      => \App\Models\Request::where('is_completed', 1)->whereBetween('request_start_time', 
                    [Carbon::now()->startOfMonth(), Carbon::now()
                    ->endOfMonth()])->sum('time') / 5000 * 100,





            'TodayEarningsTotal'      => \App\Models\Request::where('is_completed', 1)
                ->whereMonth('request_start_time', now()->month)
                ->whereDay('request_start_time', now()->day)
                ->whereYear('request_start_time', now()->year)->sum('refund_remaining'),
            'TodayEarningsTotalP'      => \App\Models\Request::where('is_completed', 1)
                ->whereMonth('request_start_time', now()->month)
                ->whereDay('request_start_time', now()->day)
                ->whereYear('request_start_time', now()->year)->sum('refund_remaining') / 5000 * 100,


            //This Week
            'TodayEarningsWeekTotal'      => \App\Models\Request::where('is_completed', 1)->whereBetween('request_start_time', 
                    [Carbon::now()->startOfWeek(), Carbon::now()])->sum('refund_remaining'),
            'TodayEarningsWeekTotalP'      => \App\Models\Request::where('is_completed', 1)->whereBetween('request_start_time', 
                    [Carbon::now()->startOfWeek(), Carbon::now()])->sum('refund_remaining') / 5000 * 100,



            //This Month
            'TodayEarningsMonthTotal'      => \App\Models\Request::where('is_completed', 1)->whereBetween('request_start_time', 
                    [Carbon::now()->startOfMonth(), Carbon::now()
                    ->endOfMonth()])->sum('refund_remaining'),
            'TodayEarningsMonthTotalP'      => \App\Models\Request::where('is_completed', 1)->whereBetween('request_start_time', 
                    [Carbon::now()->startOfMonth(), Carbon::now()
                    ->endOfMonth()])->sum('refund_remaining') / 5000 * 100,




            //This Week
            'ThisWeekDriverRegistered'      => \App\Models\Drivers::where('is_approved', 1)->whereBetween('created_at', 
                    [Carbon::now()->startOfWeek(), Carbon::now()])->count(),

            'ThisWeekTrips'      => \App\Models\Request::where('is_completed', 1)->whereBetween('request_start_time', 
                    [Carbon::now()->startOfWeek(), Carbon::now()])->count(),

            'ThisWeekAutoCancelledTrips'      => \App\Models\Request::where('is_cancelled', 1)->whereBetween('request_start_time', 
                    [Carbon::now()->startOfWeek(), Carbon::now()])->count(),

            'ThisWeekDriverRegisteredMonday'      => \App\Models\Drivers::where('is_approved', 1)
                ->whereDay('created_at', $monday)
                ->count() / 5000 * 100,
            'ThisWeekTripsMonday'      => \App\Models\Request::where('is_completed', 1)
                ->whereDay('request_start_time', $monday)->count()
                / 500 * 100,
            'ThisWeekAutoCancelledTripsMonday'      => \App\Models\Request::where('is_cancelled', 1)
                ->whereDay('request_start_time', $monday)->count()
                / 500 * 100,

            'ThisWeekDriverRegisteredTuesday'      => \App\Models\Drivers::where('is_approved', 1)
                ->whereDay('created_at', $tuesday)
                ->count() / 5000 * 100,
            'ThisWeekTripsTuesday'      => \App\Models\Request::where('is_completed', 1)
                ->whereDay('request_start_time', $tuesday)->count()
                / 500 * 100,
            'ThisWeekAutoCancelledTripsTuesday'      => \App\Models\Request::where('is_cancelled', 1)
                ->whereDay('request_start_time', $tuesday)->count()
                / 500 * 100,


            'ThisWeekDriverRegisteredWednesday'      => \App\Models\Drivers::where('is_approved', 1)
                ->whereDay('created_at', $wednesday)
                ->count() / 5000 * 100,
            'ThisWeekTripsWednesday'      => \App\Models\Request::where('is_completed', 1)
                ->whereDay('request_start_time', $wednesday)->count()
                / 500 * 100,
            'ThisWeekAutoCancelledTripsWednesday'      => \App\Models\Request::where('is_cancelled', 1)
                ->whereDay('request_start_time', $wednesday)->count()
                / 500 * 100,

            'ThisWeekDriverRegisteredThursday'      => \App\Models\Drivers::where('is_approved', 1)
                ->whereDay('created_at', $thursday)
                ->count() / 5000 * 100,
            'ThisWeekTripsThursday'      => \App\Models\Request::where('is_completed', 1)
                ->whereDay('request_start_time', $thursday)->count()
                / 500 * 100,
            'ThisWeekAutoCancelledTripsThursday'      => \App\Models\Request::where('is_cancelled', 1)
                ->whereDay('request_start_time', $thursday)->count()
                / 500 * 100,

            'ThisWeekDriverRegisteredFriday'      => \App\Models\Drivers::where('is_approved', 1)
                ->whereDay('created_at', $friday)
                ->count() / 5000 * 100,
            'ThisWeekTripsFriday'      => \App\Models\Request::where('is_completed', 1)
                ->whereDay('request_start_time', $friday)->count()
                / 500 * 100,
            'ThisWeekAutoCancelledTripsFriday'      => \App\Models\Request::where('is_cancelled', 1)
                ->whereDay('request_start_time', $friday)->count()
                / 500 * 100,

            'ThisWeekDriverRegisteredSaturday'      => \App\Models\Drivers::where('is_approved', 1)
                ->whereDay('created_at', $saturday)
                ->count() / 5000 * 100,
            'ThisWeekTripsSaturday'      => \App\Models\Request::where('is_completed', 1)
                ->whereDay('request_start_time', $saturday)->count()
                / 500 * 100,
            'ThisWeekAutoCancelledTripsSaturday'      => \App\Models\Request::where('is_cancelled', 1)
                ->whereDay('request_start_time', $saturday)->count()
                / 500 * 100,

            'ThisWeekDriverRegisteredSunday'      => \App\Models\Drivers::where('is_approved', 1)
                ->whereDay('created_at', $sunday)
                ->count() / 5000 * 100,
            'ThisWeekTripsSunday'      => \App\Models\Request::where('is_completed', 1)
                ->whereDay('request_start_time', $sunday)->count()
                / 500 * 100,
            'ThisWeekAutoCancelledTripsSunday'      => \App\Models\Request::where('is_cancelled', 1)
                ->whereDay('request_start_time', $sunday)->count()
                / 500 * 100,

             'TotalBlockedDrivers'      => \App\Models\Drivers::where('block', 1)->count(),
            'role'          => 'admin',
        ));

Потому что запросы на странице MySQL загружаются вечно, я думаю использовать индексирование, но я использую -> Где слишком много здесь и слишком много конкретных c вещей, которые могут помочь? Я не совсем уверен, как оптимизировать его, потому что для загрузки страницы требуется очень много

1 Ответ

2 голосов
/ 01 февраля 2020

Хорошо !! Давайте сделаем это.

Прежде всего, я настоятельно рекомендую использовать barryvdh/laravel-debugbar ( GitHub ). Это точно скажет вам, сколько запросов было запущено и сколько времени занял каждый из них.

Теперь давайте поговорим об оптимизации .

  • Использование select() как только возможно. Если в таблице 20 столбцов и около 1000 строк, и все, что вы делаете, это count () или sum (), то извлечение всех данных не имеет смысла.
  • Ваш \App\Models\Drivers используется несколько раз. Вот что я рекомендую:
    • Запрос 1 -> \App\Models\Drivers::where('is_approved', 1)->count();
    • Запрос 2 -> \App\Models\Drivers::where('is_approved', 0)->count();
    • Решение -> $drivers = \App\Models\Drivers::whereIn('is_approved', [0, 1])->get();
      Здесь вы можете взять adcantage из Laravel Collection
      $drivers->where('is_approved', 1)->count()
      $drivers->where('is_approved', 0)->count()
      До того, как ваш запрос выполнялся дважды, а теперь с collect () только один раз.
  • Indexing - другое решение. Проверьте это переполнение стека обсуждение .
  • Используйте caching, если можете. ( документы )
  • Еще одна вещь, которую следует учитывать, это то, как вы отображаете эти данные. Как вы сказали, страница занимает слишком много времени. Возможно, вы используете вложенные циклы. (Многое сказать не могу, поскольку я не вижу ваш блейд-файл).
  • Еще одна вещь, которую пропускают многие разработчики, - несоответствие типов данных. Если ваш столбец is_approved в sql не является целым числом, тогда запрос с помощью where(string, int) приведет к времени загрузки. Лучше иметь тот же тип данных, то есть where(int, int)

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...