【问题标题】:Make this query more efficient让这个查询更有效率
【发布时间】:2016-06-30 22:21:53
【问题描述】:

我不擅长编写处理大型数据集的查询。我想尝试一下 Laravel,看看我能想出什么。有没有更好的方法来编写这个查询并输出结果?

代码

$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);

结果

@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() !!}

另外,我在尝试加载页面时收到错误 Use of undefined constant total - assumed 'total'

任何帮助将不胜感激。谢谢!

【问题讨论】:

  • 好吧,因为它甚至不工作,“更”高效将只是工作
  • {$visitor-total}} 语法错误,缺少对象访问器方法的 &gt;。另外,您的查询有什么问题?慢吗?它不会产生预期的结果吗?
  • 你得到这个错误是因为一个错字:{{$visitor-total}} 应该是 {{$visitor->total}}
  • 您可能还想阅读Note: Currently, pagination operations that use a groupBy statement cannot be executed efficiently by Laravel. pagination
  • 是问题:{{$visitor-total}} -> {{$visitor->total}} ?

标签: php laravel


【解决方案1】:

查询看起来不错,只要它满足您的需要。

如果您的查询运行速度太慢,也许您可​​以在“id_client”列中添加索引以加快搜索速度(当然,如果您还没有)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-24
    • 2012-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-01
    相关资源
    最近更新 更多