Laravel use mysql indexing

后端 未结 1 1856
青春惊慌失措
青春惊慌失措 2020-11-30 14:41

I have this bad code (sorry) which using too many of MySQL queries sorry its too long

    return view(\'dashboard.homepage\', array(
            \'DriversNum         


        
相关标签:
1条回答
  • 2020-11-30 15:31

    Alright!! Let's do it.

    First of all, I highly recommend using barryvdh/laravel-debugbar (GitHub). This will tell you exactly how many queries were fired and how much time each one took.

    Now, let's talk about optimisation.

    • Use select() whenever possible. If a table has 20 columns and about 1000 rows and all your are doing is count() or sum() then fetching all the data doesn't make sense.
    • Your \App\Models\Drivers is being used multiple times. Here's what I recommend:
      • Query 1 -> \App\Models\Drivers::where('is_approved', 1)->count();
      • Query 2 -> \App\Models\Drivers::where('is_approved', 0)->count();
      • Solution -> $drivers = \App\Models\Drivers::whereIn('is_approved', [0, 1])->get();
        Here you can take adcantage of Laravel Collection
        $drivers->where('is_approved', 1)->count()
        $drivers->where('is_approved', 0)->count()
        Before your query was running twice and now with collect() only once.
    • Indexing is another solution. Check out this stack overflow discussion.
    • Use caching if you can. (docs)
    • Another thing to consider is how you are displaying this data. As you said the page is taking too long. Perhaps, you are using nested loops. (Can't say much since I don't see your blade file).
    • Another thing that many developers miss is data type missmatch. If your is_approved column in sql is not an integer then while querying with where(string, int) will result in load time. It's better to have same data type i.e. where(int, int)

    Hope this helps. Cheers!

    0 讨论(0)
提交回复
热议问题