From 1fbf51e09758ed4b22c4fd281433103c07510338 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 the orderBy relations that are not available in `$this->with[]`. Previously, the `$this->with` array was enhanced, but the enhanced values were not taken into account for relation Join. --- src/Query.php | 4 ++-- tests/QueryTest.php | 57 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 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..dba1f74 100644 --- a/tests/QueryTest.php +++ b/tests/QueryTest.php @@ -279,6 +279,63 @@ public function testQueryWithExpressionInOrderByThatUsesColumns() ); } + public function testOrderByJoinRequiredRelations() + { + $query = (new Query()) + ->setModel(new User()) + ->columns(['username']) + ->orderBy('user.profile.given_name', 'DESC'); + + $sql = <<assertSql($sql, $query->assembleSelect()); + } + + public function testOrderByDoNotJoinExistingRelationsAgainAndSelectAllColumnsOfWithRelation() + { + $query = (new Query()) + ->setModel(new User()) + ->with('user.profile') + ->orderBy('user.profile.given_name', 'DESC'); + + $sql = <<assertSql($sql, $query->assembleSelect()); + } + + public function testQueryWithOrderByAndWithout() + { + $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())