Skip to content

Commit 86e196c

Browse files
committed
Structures::getTotalDescendants()
Avoids 100 element count queries per structure index page
1 parent 420683b commit 86e196c

2 files changed

Lines changed: 22 additions & 8 deletions

File tree

src/services/Structures.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -296,6 +296,26 @@ public function getElementLevelDelta(int $structureId, ElementInterface $element
296296
return 0;
297297
}
298298

299+
/**
300+
* Returns the total number of descendants for a given structure element.
301+
*
302+
* @param ElementInterface $element
303+
* @return int
304+
* @since 5.2.0
305+
*/
306+
public function getTotalDescendants(ElementInterface $element): int
307+
{
308+
if (!$element->structureId || $element->lft === null || !$element->rgt === null) {
309+
return 0;
310+
}
311+
312+
return StructureElement::find()
313+
->where(['structureId' => $element->structureId])
314+
->andWhere(['>', 'structureelements.lft', $element->lft])
315+
->andWhere(['<', 'structureelements.rgt', $element->rgt])
316+
->count();
317+
}
318+
299319
// Moving elements around
300320
// -------------------------------------------------------------------------
301321

src/templates/_elements/tableview/elements.twig

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,13 @@
11
{% apply spaceless %}
22

33
{% set structure = structure is defined ? structure : null -%}
4+
{% set structuresService = structure ? craft.app.structures : null %}
45
{% set structureEditable = structureEditable is defined and not inlineEditing ? structureEditable : false -%}
56
{% set padding = craft.app.locale.getOrientation() == 'ltr' ? 'left' : 'right' -%}
67
{% set elementsService = craft.app.elements %}
78

89
{% for element in elements %}
9-
{% set totalDescendants = structure
10-
? element.getDescendants()
11-
.status(null)
12-
.drafts(null)
13-
.draftOf(false)
14-
.savedDraftsOnly()
15-
.count()
16-
: 0 %}
10+
{% set totalDescendants = structure ? structuresService.getTotalDescendants(element) : 0 %}
1711
{% set elementTitle = element.title ?: element.id %}
1812
{% set showInputs = (inlineEditing ?? false) and elementsService.canSave(element, currentUser) %}
1913
<tr data-id="{{ element.id }}"{% if structure %} data-title="{{ elementTitle }}" data-level="{{ element.level }}" data-descendants="{{ totalDescendants ?? 0 }}"{% endif %}{% if element.id in disabledElementIds %} class="disabled"{% endif %}>

0 commit comments

Comments
 (0)