由于查询,我的网站加载速度太慢

时间:2019-08-28 08:52:31

标签: php database laravel

我需要在网站上添加数据库中的某些角色-表role_users,列user_idrole_id。我正在使用此代码:

$career_solutions_data = DB::select(" 
SELECT 
career_solutions.id,
career_solutions.user_id,  
career_solutions.subject, 
career_solutions.date, 
career_solutions.public, 
career_solutions.views, 
career_solutions.optional, 
career_solutions.on_offer, 
users.username, 
users.profile_picture, 
categories.category, 
categories.category_url, 
categories.color, 
career_solutions_categories.category as sub_category,
career_solutions_format.category as event_format,
career_solutions_certification.category as certification

FROM career_solutions 

INNER JOIN categories 
ON categories.id = career_solutions.topic_category_id 

INNER JOIN career_solutions_format
ON career_solutions_format.id = career_solutions.topic_format_id

INNER JOIN career_solutions_certification
ON career_solutions_certification.id = career_solutions.topic_certification_id

INNER JOIN career_solutions_categories 
ON career_solutions_categories.id = career_solutions.topic_subcategory_id 

INNER JOIN users 
ON users.id = career_solutions.user_id 


INNER JOIN privacy_settings 
ON privacy_settings.user_id = users.id 

WHERE users.deleted_at IS NULL 
AND ( 
(privacy_settings.career_solutions = 0 AND public = 1 ) 
OR (users.id IN ( 

SELECT contacts.contact_id 
FROM contacts 
WHERE contacts.user_id = $id 
) 
) 
) 

OR users.id = $id 

ORDER BY date desc limit 5000 
"); 





我的观点:

@if($carer_solution_data['role'][0]['pivot']['role_id'] == 1 )
                                            <i style="font-size: 11px" class="icon-user"></i> 
                                            @else <i style="font-size: 11px" class="icon-hotel-restaurant-172 u-line-icon-pro fa- fa-lg"></i>

                                            @endif

这是有问题的线:

$temp_soluation['role'] = \App\User::select('id')->where('id', '=', $career_solution->user_id)->first()->role;

没有它,我的网站正在快速正确地加载。 我的网站加载速度如此之慢。我的职业解决方案上有9000多个帖子,我认为这是问题所在。这个变量$carer_solution_data['role']正在加载所有帖子,这就是我的网站的问题。我该如何避免这个问题?

1 个答案:

答案 0 :(得分:2)

您的问题不一定是您的查询,您做的事情也不会太复杂,问题在于您的浏览器被淹没了。

另一方面,您可以做一些事情来改善您的查询。  -首先,您可以使用“说明”语句为您提供有关如何生成查询以及如何改进查询的更多信息  -其次,您可以使用“索引”来改善表的关系和效率

此URL提供有关使用'Explain'语句的更多信息:http://dev.mysql.com/doc/refman/5.0/en/explain.html

正如我之前说的,您的浏览器被淹没了,因为它试图同时加载9000个(行)元素。 查看实现分页等功能,以将数据分解为较小的块。

Example of Pagination: (9000 Rows)

Chunk: 0-99 - Page 1
Chunk: 100-199 - Page 2
Chunk: 200-299 - Page 3
...

您的系统应该能够基于事件(例如,滚动到选择下一页按钮的页面底部(无限滚动),提供下一个块)向服务器发送请求。

您还可以为laravel启用事件探查器,以查看代码中的任何瓶颈: https://packagist.org/packages/jkocik/laravel-profiler