column-sortable icon indicating copy to clipboard operation
column-sortable copied to clipboard

MongoDB

Open lachlanhickey opened this issue 4 years ago • 1 comments

I haven't dived into why, but this doesn't appear to support MongoDB for some reason. Any immediate thoughts?

lachlanhickey avatar Sep 15 '20 03:09 lachlanhickey

here is what I did

namespace App\Traits\Model;

use BadMethodCallException;
use Illuminate\Support\Str;
use Kyslik\ColumnSortable\Exceptions\ColumnSortableException;
use Kyslik\ColumnSortable\SortableLink;

trait Sortable
{
    use \Kyslik\ColumnSortable\Sortable;

    /**
     * @param \Illuminate\Database\Query\Builder $query
     * @param array                              $sortParameters
     *
     * @return \Illuminate\Database\Query\Builder
     *
     * @throws ColumnSortableException
     */
    private function queryOrderBuilder($query, array $sortParameters)
    {
        $model = $this;

        [$column, $direction] = $this->parseParameters($sortParameters);

        if (is_null($column)) {
            return $query;
        }

        $explodeResult = SortableLink::explodeSortParameter($column);
        if ( ! empty($explodeResult)) {
            $relationName = $explodeResult[0];
            $column       = $explodeResult[1];

            try {
                $relation = $query->getRelation($relationName);
                $query    = $this->queryJoinBuilder($query, $relation);
            } catch (BadMethodCallException $e) {
                throw new ColumnSortableException($relationName, 1, $e);
            } catch (\Exception $e) {
                throw new ColumnSortableException($relationName, 2, $e);
            }

            $model = $relation->getRelated();
        }

        if (method_exists($model, Str::camel($column).'Sortable')) {
            return call_user_func_array([$model, Str::camel($column).'Sortable'], [$query, $direction]);
        }

        if (isset($model->sortableAs) && in_array($column, $model->sortableAs)) {
            $query = $query->orderBy($column, $direction);
        } elseif ($this->columnExists($model, $column)) {
            if(!($model instanceof \Jenssegers\Mongodb\Eloquent\Model)) {
                $column = $model->getTable().'.'.$column;
            }
            $query  = $query->orderBy($column, $direction);
        }

        return $query;
    }
}

and then use this trait on your model.

vinkev avatar Oct 09 '20 03:10 vinkev