Laravel-Yajra DataTable:如何在对其他列进行排序时阻止索引列(具有行序列号)的更改



我正在为Laravel 8应用程序使用Yajra DataTable。除了一个小问题外,所有Yajra DT功能都运行良好。我的第一列是DT_RowIndex,已添加为->addIndexColumn((。这些是行序列号(1,2,3…(。自然地,在这一列上排序是错误的。但是,当对其他列进行排序时,这些序列号也会随之进行排序。我希望在对表进行排序时,此列保持固定。有人能为这个问题提出解决方案吗。下面是我正在使用的代码。

控制器:

public function index(Request $request)
{
if ($request->ajax()) 
{
$hospitals = Hospital::join('District', 'District.dt_id', '=', 'Hospital.dt_id')
->join('Tehsil', 'Tehsil.teh_id', '=', 'Hospital.teh_id')
->orderBy('District.dt_name', 'asc')->orderBy('Tehsil.teh_name', 'asc')
->get(['Hospital.hl_id', 'Hospital.hl_name','Tehsil.teh_name', 'District.dt_name', 'Hospital.assessment_status']);

return Datatables::of($hospitals)
->addIndexColumn()
->addColumn('action', function($row){
$btn = '<a href="/hospital/'.$row->hl_id.'" class="btn btn-info btn-sm text-center">View</a>&nbsp;&nbsp;';
$btn = $btn.'<a href="/hospital/'.$row->hl_id.'/edit" class="edit btn btn-primary btn-sm text-center">Edit</a>&nbsp;&nbsp;';
$btn = $btn.'<a href="'.route('HospitalDeleteRoute', $row->hl_id).'" class="btn btn-danger btn-sm" onclick="return confirm('Are you sure you want to delete the hospital: '.$row->hl_name.'')">Delete</a>'; 

return $btn;
})
->rawColumns(['action'])
->make(true);
}
return view('hospitals.index');
}

索引php文件

<table class="table table-sm table-striped table-bordered hospital-DT" id="tbl_hosp">
<thead class="thead-dark" align="center">
<tr class="th_sort_color">
<th>S/No</th>
<th>Hospital Name</th>
<th>Tehsil</th>
<th>District</th>
<th>Assessment Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

脚本:

$(function () {
var table = $('.hospital-DT').DataTable({
processing: true,
serverSide: false,
searchable: true,
orderable:true,
order: [],
lengthMenu: [[10, 25, 50, 100, 500], [10, 25, 50, 100, 500]],
ajax: "{{ route('hospital.index') }}",
'columns': [
{data: 'DT_RowIndex', name: '', orderable: false, searchable: false},
{data: 'hl_name', name: 'name'},
{data: 'dt_name', name: 'name'},
{data: 'teh_name', name: 'name'},
{data: 'assessment_status', name: 'name'},
{data: 'action', name: 'action', orderable: false, searchable: false}
],
//      'columnDefs': [ {
//      'targets': [0,5], /* column index */
//      'orderable': false, /* true or false */
//   }]
});
});

您可以从查询中获取行的索引,我使用ms.sql并执行以下操作:

$hospitals = Hospital::select([
DB::raw('ROW_NUMBER() OVER(ORDER BY id ASC) AS rownum')
])->...

从那里,您可以获得rownum作为行的索引列,并在脚本中调用它,您可以更改此代码"ORDER BY id ASC";得到你想要的。。

最新更新