简体   繁体   English

Laravel 很慢 eloquent 查询

[英]Laravel very slow eloquent query

I need to get catalogs from database using Laravel query, so I write simply:我需要使用 Laravel 查询从数据库中获取目录,所以我简单地写了:

   $catalogs = Catalog::where('shop_id', $shop->id)->latest()->get(['id','title', 'created_at', 'shop_id', 'cover_bg', 'frontpage', 'pdf', 'clicks', 'finished']);

In a catalog table I have more than 100 columns - 2 of them are with type longtext .在目录表中,我有 100 多列 - 其中 2 列的类型为longtext Catalog currently contain around 14000 records and fetching data is very slow:目录目前包含大约 14000 条记录并且获取数据非常慢:

Here is phpMyAdmin execution time这里是phpMyAdmin的执行时间

在此处输入图像描述

Here is Laravel query execution time:下面是 Laravel 查询执行时间: 在此处输入图像描述

How I can speed up my query?如何加快查询速度? I think 14 000 records are not big table.我认为 14 000 条记录不是大表。 Also as you can see I try to avoid my longtext columns so I didnt fetch them.同样如您所见,我尽量避免使用长文本列,所以我没有获取它们。

Is it problem with a server performance or something else?是服务器性能问题还是其他问题?

Also CPU very low: CPU 也很低: 在此处输入图像描述

I think you can speed up your query by adding index statement to the shop_id in your table structure.我认为您可以通过将索引语句添加到表结构中的 shop_id 来加快查询速度。 visit https://www.sqlshack.com/sql-index-overview-and-strategy/访问https://www.sqlshack.com/sql-index-overview-and-strategy/

Try switching to using raw query, not Eloquent by using DB::select(DB::raw('...'))尝试使用DB::select(DB::raw('...'))切换到使用原始查询,而不是 Eloquent

This is because something called N+1 Query Issue that rapidly increases the total queries..这是因为称为 N+1 查询问题的东西会迅速增加总查询量。

I recommend you to read this article我建议你阅读这篇文章

https://laravel-news.com/laravel-n1-query-problems https://laravel-news.com/laravel-n1-query-problems

The problem is from the get part so you need to add the required columns in the select like this问题出在get部分,因此您需要像这样在select中添加所需的列

  $catalogs = Catalog::select('id','title', 'created_at', 'shop_id', 'cover_bg', 'frontpage', 'pdf', 'clicks', 'finished')->where('shop_id', $shop->id)->latest()->get();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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