Kyslik/column-sortable

sort relation column

Closed this issue · 3 comments

image

I got this error when I tried to sort a belongsTo relation :

relation method

  public function model()  
    {
        return $this->belongsTo(BrandModel::class, 'brand_model_id', 'id');
    }

inverse relation :

public function repaired()
    {
        return $this->hasOne(RepairedDevice::class);

    }

in index

<th class="text-center text-primary">@sortablelink('model.name', __('repaired.model')) </th>

can you show me your controller please ?

public function index(Request $request)
{
$rowPerPage = [5, 10, 15, 20, 25];
$searchText = $request->query('search');
$per_page = 25;
$repairedQuery = RepairedDevice::query();
if ($searchText) {
$repairedQuery->whereHas('customer', function ($query) {
$query->where('customers.full_name', 'like', '%' . request('search') . '%');
})->orWhereHas('employee', function ($query) {
$query->where('employees.first_name', 'like', '%' . request('search') . '%');
})->orWhere('imei', 'like', '%' . $searchText . '%')
->orWhereHas('model', function ($query) use ($searchText) {
$query->where('brand_models.name', 'like', '%' . $searchText . '%')->orWhereHas('brand', function ($q) use ($searchText) {
$q->where('brands.name', 'like', '%' . $searchText . '%');
});;
});
}

if ($request->status) { 
    $repairedQuery->where('status' , $request->status);
}
     

$sortColumn = $request->query('sort', 'created_at');
$sortDirection = $request->query('direction', 'desc');

$repairedQuery->orderBy($sortColumn, $sortDirection);
if ($request->pagination)
    $per_page = $request->pagination;
$repairedDevices = $repairedQuery->sortable()->paginate($per_page)->withQueryString();
$count = $repairedDevices->count();
return view('repaired.index', compact('repairedDevices', 'count', 'rowPerPage'));

}

you can not sort two times
try to remove this code $sortColumn = $request->query('sort', 'created_at');
$sortDirection = $request->query('direction', 'desc');

$repairedQuery->orderBy($sortColumn, $sortDirection);