简体   繁体   中英

Make this query more efficient

I'm terrible at writing queries that are dealing with large datasets. I wanted to take a stab at Laravel and see what I can come up with. Is there a better way to write this query and output the results?

Code

$visitors = DB::table('visitors')
            ->where('id_client',1)
            ->select('id', 'ip', DB::raw('count(*) as total'), 'date', 'city', 'region')
            ->groupBy('ip')
            ->orderBy('date', 'DESC')
            ->simplePaginate(25);

Results

@foreach($visitors as $visitor)
               <tr>
                        <td>
                            {{$visitor->id}}
                        </td>
                        <td>
                            @if (date('F d, Y', strtotime($visitor->date)) === date('F d, Y'))
                                Today
                            @else
                                {{ date('F d, Y', strtotime($visitor->date)) }}
                            @endif  
                        </td> 
                        <td>
                            {{$visitor-total}}
                        </td>                       
                        <td>
                            {{$visitor->city}}
                        </td>
                        <td>
                            {{$visitor->region}}
                        </td>
                 </tr>
          @endforeach

          {!! $visitors->render() !!}

Also, I get the error Use of undefined constant total - assumed 'total' when I try to load the page.

Any help would be greatly appreciated. Thanks!

The query looks good as long as it does what you need.

If your query runs too slow, maybe you can add an index to your 'id_client' column to make the search faster (if you don't have it already of course).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM