没有不值得去解决的问题,也没有不值得去学习的技术!

Handling the N+1 Problem When You Assign Extra Fields to Individual Records During Array Traversal in Laravel 6

This caused an N + 1 problem. Checking the number of generated SQL queries revealed 79 queries, an extra increase of 25 queries (because with was used, it actually increased by 50 query SQLs)

1. In Laravel 6, when querying a list (converted to an array), the reason it must be converted to an array is that the current requirement is to assign extra fields to individual records during the traversal. This extra field does not exist in the model.

PHP

$wpThemes = Theme::select('id', 'custom_name', 'name', 'is_original', 'is_default', 'created_at_gmt', 'updated_at_gmt', 'original_theme_name')
            ->orderBy('updated_at_gmt', 'desc')
            ->get()->toArray();

foreach ($wpThemes as $wpTheme) {
	$wpThemeObject = $this->get($wpTheme['id']);
	$wpTheme['updatable'] = $this->isActionable($saasThemeConfig, $wpThemeObject, 'updatable');
}


2. This caused an N + 1 problem. Checking the number of generated SQL queries revealed 79 queries, an extra increase of 25 queries (because with was used, it actually increased by 50 query SQLs). As shown in Figure 1.

This caused an N + 1 problem. Checking the number of generated SQL queries revealed 79 queries, an extra increase of 25 queries (because with was used, it actually increased by 50 query SQLs)
Figure 1

3. Finally, I decided to query the list in Laravel 6 (without converting to an array), and during the traversal, convert the individual object to an array.

PHP

$wpThemes = Theme::select('id', 'custom_name', 'name', 'is_original', 'is_default', 'created_at_gmt', 'updated_at_gmt', 'original_theme_name')
            ->orderBy('updated_at_gmt', 'desc')
            ->get();

foreach ($wpThemes as $wpTheme) {
	$wpThemeArray = $wpTheme->toArray();
	$wpThemeObject = $this->get($wpThemeArray['id']);
	$wpThemeArray['updatable'] = $this->isActionable($saasThemeConfig, $wpTheme, 'updatable');
}


4. Checking the number of generated SQL queries revealed 22 queries. The 50 extra query SQLs that were actually added before have now been eliminated. This meets expectations. As shown in Figure 2.

Checking the number of generated SQL queries revealed 22 queries. The 50 extra query SQLs that were actually added before have now been eliminated. This meets expectations
Figure 2

关于作者 · 持续学习与技术实践

我是一名拥有 15 年以上开发经验的技术从业者,自 2013 年起持续运营个人技术博客,记录工作与个人项目中遇到的真实问题,以及解决问题过程中的探索、实践和思考。

除了技术写作,我也在持续开发和维护自己的独立项目,探索新技术和新工具在实际场景中的应用。我始终相信,没有不值得去解决的问题,也没有不值得去学习的技术。

如果这篇文章对你有所帮助,欢迎浏览博客中的其他文章,也欢迎交流技术经验与想法。

关于我  ·  GitHub  ·  邮件联系