My page takes 3-5 whole minutes to load, how can I

2019-08-05 06:15发布

I'm currently working on this project and the main page takes nearly 5 whole minutes to load. I've been trying to reduce the runtime, but I'm still new to programming and I'm not too familiar with pthreads, but I was told pthreads wouldn't work with this. Can someone help me figure out how to run this code faster and stop Chrome from killing the processor?

Also I know my PHP code is a bit messy, was planning on cleaning it up later, but the little bits of PHP code are around lines 0, 270, 420, 560, etc throughout the entire page.

Thank you for your time.

Here's a snippet of the code, but you can find the entire code in the pastebin linked below:

<?php $k = 0; ?>

<tr>
    @foreach($mondays as $monday)
    <?php $shift_worker_id = DB::table('schedule')->where('id', $monday->id)->value('shift_worker_id') ?>
    <?php $zone_id = DB::table('schedule')->where('id', $monday->id)->value('zone_id') ?>
    <?php $zone = DB::table('zone')->where('id', $zone_id)->value('name') ?>
    <?php $worker_id = DB::table('shift_worker')->where('id', $shift_worker_id)->value('worker_id') ?>
    <?php $shift_id = DB::table('shift_worker')->where('id', $shift_worker_id)->value('shift_id') ?>
    <?php $time = DB::table('shift')->where('id', $shift_id)->value('time') ?>
    <?php $type = DB::table('shift')->where('id', $shift_id)->value('type') ?>
    <?php $name = DB::table('worker')->where('id', $worker_id)->value('name') ?>
    @if($type == "Graveyard")
        <th style="font-size:11px" colspan="1">{{$name}}</th>
        <th style="font-size:7px" colspan="1">{{$time}}</th>
        <th style="font-size:11px" colspan="1">{{$zone}}</th>
        <th colspan="1"></th>
        <th colspan="1"></th>
        <th colspan="1"></th>
        <?php $k++; ?>
    @endif
    @if($k % 4 == 0)
        </tr>
        <tr>
    @endif
    @endforeach
</tr>

https://pastebin.com/uUGrs1x0

1条回答
\"骚年 ilove
2楼-- · 2019-08-05 06:19

It's definitely because of N+1 problem. Learn how to use eager loading.

You're creating a lot of redundant queries to the DB inside the loop, probably thousands instead of just 6.

Eloquent can "eager load" relationships at the time you query the parent model. Eager loading alleviates the N + 1 query problem.

https://laravel.com/docs/5.5/eloquent-relationships#eager-loading

查看更多
登录 后发表回答