From a1a2e20c343dfbb1cd88638ab438eeb0c5b5d76e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Burak=20Sormage=C3=A7?= Date: Fri, 8 Jan 2021 03:34:11 +0300 Subject: [PATCH] Orderby new features (#744) * Update README.md * added secondary param to orderby relation --- README.md | 12 ++++++++++++ src/Prettus/Repository/Criteria/RequestCriteria.php | 11 +++++++++-- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 0f5fc77d..c151d2e7 100644 --- a/README.md +++ b/README.md @@ -760,6 +760,18 @@ ORDER BY posts.title ... ``` +`http://prettus.local/users?orderBy=posts:custom_id,other_id|posts.title&sortedBy=desc` + +Query will have something like this + +```sql +... +INNER JOIN posts ON users.custom_id = posts.other_id +... +ORDER BY posts.title +... +``` + Sorting multiple columns same sortedBy `http://prettus.local/users?orderBy=name;created_at&sortedBy=desc` diff --git a/src/Prettus/Repository/Criteria/RequestCriteria.php b/src/Prettus/Repository/Criteria/RequestCriteria.php index f007b79b..efe1bb67 100644 --- a/src/Prettus/Repository/Criteria/RequestCriteria.php +++ b/src/Prettus/Repository/Criteria/RequestCriteria.php @@ -190,9 +190,16 @@ protected function parserFieldsOrderBy($model, $orderBy, $sortedBy) $sortColumn = $split[1]; $split = explode(':', $sortTable); - if(count($split) > 1) { + $localKey = '.id'; + if (count($split) > 1) { $sortTable = $split[0]; + + $commaExp = explode(',', $split[1]); $keyName = $table.'.'.$split[1]; + if (count($commaExp) > 1) { + $keyName = $table.'.'.$commaExp[0]; + $localKey = '.'.$commaExp[1]; + } } else { /* * If you do not define which column to use as a joining column on current table, it will @@ -206,7 +213,7 @@ protected function parserFieldsOrderBy($model, $orderBy, $sortedBy) } $model = $model - ->leftJoin($sortTable, $keyName, '=', $sortTable.'.id') + ->leftJoin($sortTable, $keyName, '=', $sortTable.$localKey) ->orderBy($sortColumn, $sortedBy) ->addSelect($table.'.*'); } else {