Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MongoDB #166

Open
lachlanhickey opened this issue Sep 15, 2020 · 1 comment
Open

MongoDB #166

lachlanhickey opened this issue Sep 15, 2020 · 1 comment

Comments

@lachlanhickey
Copy link

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

@vinkev
Copy link

vinkev commented Oct 9, 2020

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants