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())