Skip to content

Commit

Permalink
Merge pull request #1 from rtakauti/master
Browse files Browse the repository at this point in the history
Sortable column add feature - orderByRaw
  • Loading branch information
pedro-lucas committed May 2, 2016
2 parents 1bb81ee + f598e8e commit fdd30e8
Showing 1 changed file with 13 additions and 7 deletions.
20 changes: 13 additions & 7 deletions src/ColumnSortable/Sortable.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Kyslik\ColumnSortable\Exceptions\ColumnSortableException;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Query\Builder;

use Kyslik\ColumnSortable\Exceptions\ColumnSortableException;
/**
* Trait Sortable.
*/
Expand Down Expand Up @@ -70,6 +70,7 @@ private function queryJoinBuilder($query, $relations)
$query = $query->leftJoin($relatedModel->getTable(), $relatedKey, '=', $parentKey);

$baseQuery = $relation->getQuery();

}

return $relation->getRelated();
Expand All @@ -89,8 +90,9 @@ private function queryOrderBuilder($query, array $a)
$sortList = $this->getSortable();
$sortKey = array_get($a, 'sort', null);
$sortName = $sort = array_get($sortList, $sortKey, $sortKey);
$isRawSort = strpos($sortName, 'FIELD(') === 0;

if(!$this->sortExists($this, $sortName)) { //ignore integer sortable keys
if(!$this->sortExists($this, $sortName)) { //Ignore integer sortable keys
return $query;
}

Expand All @@ -101,15 +103,18 @@ private function queryOrderBuilder($query, array $a)
if (!is_null($sort)) {
$relations = $this->getSortRelations($sort);

if (!is_null($relations)) {
if (!is_null($relations) && !$isRawSort) {
$model = $this->queryJoinBuilder($query, $relations['relations']);
$sort = $relations['field'];
}

$sort = $model->getTable() . '.' . $sort;

if ($this->sortExists($this, $sortName)) {
$query = $query->orderBy($sort, $order);
if(strpos($sortName, 'FIELD(') === 0){
$query = $query->orderByRaw($sortName . ' ' . $order);
}else{
$sort = $model->getTable() . '.' . $sort;
$query = $query->orderBy($sort, $order);
}
}

}
Expand Down Expand Up @@ -143,6 +148,7 @@ public static function link(array $parameters) //Extending Blade; Blade sends ar
if (Input::get('sort') == $sortOriginal && in_array(Input::get('order'), ['asc', 'desc'])) {
$asc_suffix = Config::get('columnsortable.asc_suffix', '-asc');
$desc_suffix = Config::get('columnsortable.desc_suffix', '-desc');

$icon = $icon . (Input::get('order') === 'asc' ? $asc_suffix : $desc_suffix);
} else {
$icon = Config::get('columnsortable.sortable_icon');
Expand Down Expand Up @@ -192,4 +198,4 @@ public function getSortable() {
private function sortExists($model, $column) {
return in_array($column, $model->getSortable());
}
}
}

0 comments on commit fdd30e8

Please sign in to comment.