From d20d50821006b5d15fe0b581b8e2695fb9223dd1 Mon Sep 17 00:00:00 2001 From: Kevinn1109 <7937169+Kevinn1109@users.noreply.github.com> Date: Thu, 12 Dec 2024 16:58:22 +0100 Subject: [PATCH] FIX Use ORM functions to perform eager loading instead of raw query --- src/ORM/DataList.php | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/src/ORM/DataList.php b/src/ORM/DataList.php index 72ccacd7113..d5041292f66 100644 --- a/src/ORM/DataList.php +++ b/src/ORM/DataList.php @@ -5,6 +5,7 @@ use SilverStripe\Core\Injector\Injector; use SilverStripe\Dev\Debug; use SilverStripe\ORM\Queries\SQLConditionGroup; +use SilverStripe\ORM\Queries\SQLSelect; use SilverStripe\View\ViewableData; use Exception; use InvalidArgumentException; @@ -1349,6 +1350,10 @@ private function fetchEagerLoadManyMany( $fetchList = $relationList->forForeignID($parentIDs); $fetchList = $this->manipulateEagerLoadingQuery($fetchList, $relationChain, $relationType); $fetchedRows = $fetchList->getFinalisedQuery(); + $query = $fetchList->dataQuery()->query(); + $fetchedOrderBy = $query->getOrderBy(); + $childTables = $query->queriedTables(); + $childTable = reset($childTables); foreach ($fetchedRows as $row) { $fetchedRowsArray[$row['ID']] = $row; @@ -1361,15 +1366,14 @@ private function fetchEagerLoadManyMany( $joinRows = []; if (!empty($parentIDs) && !empty($fetchedIDs)) { $fetchedIDsAsString = implode(',', $fetchedIDs); - $joinRows = DB::query( - 'SELECT * FROM "' . $joinTable - // Only get joins relevant for the parent list - . '" WHERE "' . $parentIDField . '" IN (' . implode(',', $parentIDs) . ')' - // Exclude any children that got filtered out - . ' AND ' . $childIDField . ' IN (' . $fetchedIDsAsString . ')' - // Respect sort order of fetched items - . ' ORDER BY FIELD(' . $childIDField . ', ' . $fetchedIDsAsString . ')' - ); + $joinRows = SQLSelect::create() + ->setSelect('"' . $joinTable . '".' . "*") + ->setFrom([$joinTable => $joinTable]) + ->addWhere('"' . $parentIDField . '" IN (' . implode(',', $parentIDs) . ')') + ->addWhere('"' . $childIDField . '" IN (' . $fetchedIDsAsString . ')') + ->addLeftJoin($childTable, "$childTable.ID = $joinTable.$childIDField") + ->setOrderBy($fetchedOrderBy) + ->execute(); } // Store the children in an EagerLoadedList against the correct parent