【问题标题】:Laravel query slow to fetch data from databaseLaravel 查询从数据库中获取数据很慢
【发布时间】:2021-08-20 10:54:22
【问题描述】:

我有一个 Laravel API 和一个内置于 Nuxt JS 的前端。在我的一个前端页面上,我正在显示来自我的一个数据库表的应用程序的分页列表(客户数据),向我的端点发出的请求和函数applications 去并以分页列表的形式从数据库中获取数据。

但问题是,考虑到我不会对数据进行太多处理,而且我的数据库表没有那么多列,这感觉很慢。

我的应用程序表的架构是:

Schema::create('applications', function (Blueprint $table) {
    $table->id();
    $table->string('hash', 42)->index();
    $table->string('product_type')->nullable();
    $table->string('email')->nullable()->index();
    $table->date('birthday')->nullable()->index();
    $table->string('postcode')->nullable()->index();
    $table->string('mobile')->nullable()->index();
    $table->text('data');
    $table->timestamps();
    $table->timestamp('verified_at')->nullable();
});

有问题的功能是:

/**
 * Applications
 */
public function getApplications()
{

    $applications = Application::orderBy('created_at', 'desc')
                               ->paginate(25);

    foreach ($applications as $key => $applicant) {
      try {
        $applications[$key]['data'] = json_decode($applicant['data']);
      } catch (\Exception $e) { }
    }

    return $applications;

}

/**
 * All applications
 *
 * @param  Request  $request
 */
public function applications(Request $request)
{

    try {

      // daily graphs
      $applications = $this->getApplications();

      // not set or nothing to report
      if (!$applications) {
        return response()->json([
          'success' => false,
          'msg' => 'No applications found, check back in a few minutes',
        ], 422);
      }

      // return the response
      return response()->json([
        'success' => true,
        'msg' => 'Icicle applications',
        'applications' => $applications ?? null
      ], 200);

    } catch (\Exception $e) {

      // return default template
      return response()->json([
        'success' => false,
        'msg' => 'We were unable to load applications right now',
      ], 422);

    }

}

我尝试将paginate 更改为简单的get,并且我还尝试通过Tinker 运行相同的查询,我进一步尝试完全删除我的foreach 循环,看看这是否会提高性能。

获取数据需要 7 秒,其中我有 200 万条记录,我觉得这应该快得多,因为它是一个简单的查询,我的查询中是否缺少某些内容或我获取数据的方式?

【问题讨论】:

  • 你能不试试orderBy吗?也可以使用simplePaginate()。

标签: php sql laravel laravel-query-builder


【解决方案1】:

一些建议

  1. 索引“created_at”列并删除其他索引(如果它们是不必要的)。

  2. 使用 simplePaginate() - https://laravel.com/docs/8.x/pagination#simple-pagination

  3. 如果您使用的是 laravel 8,请尝试光标分页 - https://laravel.com/docs/8.x/pagination#cursor-pagination

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    • 2021-01-18
    • 1970-01-01
    • 2015-08-17
    相关资源
    最近更新 更多