Querying list (converted to array) in Laravel 6, you need to assign additional fields of a single record during the traversal process, and you need to use a single object, which in turn leads to the handling of n + 1 problems
1. Query the list (converted to an array) in Laravel 6, why you have to convert it to an array, the reason is that the current requirements are additional fields that need to be assigned a single record during the traversal process. This extra field does not exist in the model.
$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. Cause the occurrence of N + 1 problem, check the number of generated SQL, 79, and add 25 queries (because the use of with, actually add 50 query sql). as shown in Figure 1
3. The final decision is to query the list in Laravel 6 (not converted to an array), and during the traversal process, convert a single object into an array.
$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. Check the number of generated SQL, it is 22, and 50 additional queries are actually added before, but now it has been canceled. in line with expectations. as shown in Figure 2

