codekerala / spa-laravel-vuejs

Single Page Application with Laravel 5.3 and Vue.js 2.1.x
https://codekerala.com
153 stars 82 forks source link

Sorting related column #2

Open re1naldo opened 7 years ago

re1naldo commented 7 years ago

Is it possible to sort grid by column from different table? For example, I would like to sort grid by customer name on Invoice page:

export default {
     name: 'InvoiceIndex',        
     data() {
         return {
     ...
             thead: [
                 {title: 'Customer', key: 'customer.name', sort: true},
             ],
         }
     },
     components: {
         DataViewer
     }
}

I tried to modify FilterPaginateOrder.php:

public function scopeFilterPaginateOrder($query)
{
    ...

    if($this->isRelatedColumn($request->column)) {
        list($relation, $relatedColumn) = explode('.', $request->column);

        return $query->whereHas($relation, function($query) use ($relatedColumn, $request) {
                $q = $this->filterColumn($query, $request);
                return $q->orderBy($relatedColumn, $request->direction);
            })
            ->paginate($request->per_page);
    } else {
        return $query->orderBy($request->column, $request->direction)
            ->where(function($query) use ($request) {
                return $this->filterColumn($query, $request);
            })
            ->paginate($request->per_page);
    }
}

protected function isRelatedColumn($column)
{
    return strpos($column, '.') !== false;
}

protected function filterColumn($query, $request)
{
    // check if search query is empty
    if($request->has('search_query_1')) {
        // determine the type of search_column
        // check if its related model, eg: customer.id
        if($this->isRelatedColumn($request->search_column)) {
            list($relation, $relatedColumn) = explode('.', $request->search_column);
            return $query->whereHas($relation, function($query) use ($relatedColumn, $request) {
                return $this->buildQuery(
                    $relatedColumn,
                    $request->search_operator,
                    $request,
                    $query
                );
            });
        } else {
            // regular column
            return $this->buildQuery(
                $request->search_column,
                $request->search_operator,
                $request,
                $query
            );
        }
    }

    return $query;
}

but the data was not sorted properly.