yajra / laravel-datatables

jQuery DataTables API for Laravel
https://yajrabox.com/docs/laravel-datatables
MIT License
4.77k stars 858 forks source link

To remove the defaultOrder, what should I do? #3110

Closed nalcoder0913 closed 10 months ago

nalcoder0913 commented 10 months ago

Summary of problem or feature request

When no sorting column is selected:

select * from `myTable` order by `created_at` desc limit 10 offset 0

When a sorting column is selected:

select * from `myTable` order by `created_at` desc, `code` desc limit 10 offset 0

When I want to change the sorting order, I would like to remove "created_at." How can I achieve this?

Code snippet of problem

$data = MyTable:latest();
return DataTables::eloquent($data)
                    ->addIndexColumn()
                    ->addColumn('product_id', function ($row) {
                        return Product::find($row->product_id)->product_name;
                    })
                    ->addColumn('project_id', function ($row) {
                        return Project::find($row->project_id)->name;
                    })
....(more addColumn)....
                    ->order(function ($query) {
                        if (request()->has('order.0.column') && !empty(request()->input('order.0.column'))) {
                            $orderColumnIndex = request()->input('order.0.column');
                            $orderColumn = request()->input('columns.' . $orderColumnIndex . '.data');
                            $orderDir = request()->input('order.0.dir');
                            $query->orderBy($orderColumn, $orderDir);
                        }
                    })
                    ->toJson();

System details

nalcoder0913 commented 10 months ago

I'm sorry. It seems like the issue was with the code MyTable:;latest();. I've now changed it to MyTable::query();