From 8f69a0717a3dbff9d6a8a6725008014ecd5d5b57 Mon Sep 17 00:00:00 2001 From: Sukhwinder Dhillon Date: Wed, 22 Jan 2025 16:42:15 +0100 Subject: [PATCH] Query::assembleSelect(): Apply `orderBy` before joining the relations Otherwise, the query fails if `Query::orderBy()` contain relations that are not present in `Query::$with`. - Previously, `Query::order()` enhanced the `Query::$with` array, but the enhanced values were no longer taken into account for joining relations. --- src/Query.php | 4 ++-- tests/QueryTest.php | 56 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 2 deletions(-) diff --git a/src/Query.php b/src/Query.php index c82e2e7..0428068 100644 --- a/src/Query.php +++ b/src/Query.php @@ -491,6 +491,8 @@ public function assembleSelect() $select->where(...array_reverse($where)); } + $this->order($select); + $joinedRelations = []; foreach ($this->getWith() + $this->getUtilize() as $path => $_) { foreach ($resolver->resolveRelations($path) as $relationPath => $relation) { @@ -548,8 +550,6 @@ public function assembleSelect() $select->offset($this->getOffset()); } - $this->order($select); - $this->emit(static::ON_SELECT_ASSEMBLED, [$select]); return $select; diff --git a/tests/QueryTest.php b/tests/QueryTest.php index 898df7b..1f4ae3c 100644 --- a/tests/QueryTest.php +++ b/tests/QueryTest.php @@ -279,6 +279,62 @@ public function testQueryWithExpressionInOrderByThatUsesColumns() ); } + public function testOrderByJoinRequiredRelationsButDoNotSelectTheirColumns() + { + $query = (new Query()) + ->setModel(new User()) + ->orderBy('user.profile.given_name', 'DESC'); + + $sql = <<assertSql($sql, $query->assembleSelect()); + } + + public function testOrderByDoNotJoinExistingRelationsAgain() + { + $query = (new Query()) + ->setModel(new User()) + ->with('user.profile') + ->orderBy('user.profile.given_name', 'DESC'); + + $sql = <<assertSql($sql, $query->assembleSelect()); + } + + public function testOrderByJoinsWithoutRelation() + { + $query = (new Query()) + ->setModel(new User()) + ->without('user.profile') + ->orderBy('user.profile.given_name', 'DESC'); + + $sql = <<assertSql($sql, $query->assembleSelect()); + } + public function testExplicitColumnsDontCauseRelationsToBeImplicitlySelected() { $query = (new Query())