我是 Laravel 的新手,正在尝试使用 Yajra Datatable 插件实现服务器端功能。插件在少量记录的情况下运行良好,但我有大约 100000 条记录。
为了加快控制器中的处理速度,我使用 take(10) 限制查询结果,并使用另一个查询来计算总结果数目。到目前为止一切都很好。
问题在于如何管理搜索。除了主要的搜索字段外,我还使用了逐列搜索,但不知道如何返回正确的记录数量以管理带有逐列搜索过滤器的分页。
我认为每个搜索关键字都在 $columns = $request->get('columns');
中,但不知道如何管理计数查询。
感谢您宝贵的建议。
HTML 视图代码:
<table id="oTable">
<thead>
<tr>
<th>Action</th>
<th>Brand</th>
<th>Code</th>
<th>Description</th>
</tr>
<tr>
<th class="no_search"></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
</table>
Jquery 代码:
$('#oTable').DataTable({
dom: 'lfrtip',
"processing": true,
"serverSide": true,
"ajax": '{!! url('getRecords') !!}',
"columns": [
{data: 'items.id', name: 'items_id'},
{data: 'brands.description', name: 'brands_description'},
{data: 'items.code', name: 'items_code'},
{data: 'items.description', name: 'items_description'}
],
columnDefs: [
{targets: 'no_sort', orderable: false}
],
initComplete: function () {
this.api().columns().every(function () {
var column = this;
var columnClass = column.header().className;
if (columnClass.indexOf('no_search') != false) {
var input = document.createElement("input");
$(input).addClass('form-control');
$(input).appendTo($(column.header()).empty())
.on('change', function () {
column.search($(this).val(), false, false, true).draw();
});
}
});
}
});
控制器的方法:
public function getRecords(Request $request) {
$search = $request->input('search.value');
$columns = $request->get('columns');
$count_total = \DB::table('items')
->join('brands', 'item.brand', '=', 'brands.code')
->count();
$count_filter = \DB::table('items')
->join('brands', 'items.brand', '=', 'brands.code')
->where( 'brands.description' , 'LIKE' , '%'.$search.'%')
->orWhere( 'items.description' , 'LIKE' , '%'.$search.'%')
->orWhere( 'items.code' , 'LIKE' , '%'.$search.'%')
->count();
$items= \DB::table('items')
->join('brands', 'items.brand', '=', 'brands.code')
->select(
'items.id as items_id',
'items.code as items_code',
'items.description as items_description',
'brands.description as brands_description'
) -> take(10);
return Datatables::of($items)
->with([
"recordsTotal" => $count_total,
"recordsFiltered" => $count_filter,
])
->rawColumns(['items_id','brands_description'])
->make(true);
}