问题描述
使用Yajra Datables,Laravel返回“内存耗尽...”错误消息。 实际上,我们如何直接将过滤和排序应用于SQL,而不是让服务器端处理过滤和排序。
Laravel控制器
// Table1 has 200,000 rows,the query itself is also slow
$rs = DB::select("select *
from Table1");
$numrow = count($rs);
if ($numrow > 0) {
foreach ($rs as $row) {
$column1 = $row_customers->column1;
$arr['col1'] = $column1;
$arrs[] = $arr;
}
}
$response = Datatables::of($arrs)->make(true)->getData(true);
return response()->json($response);
Laravel视图
$('#Table1').DataTable({
processing: true,serverSide: true,responsive: true,cache: false,ajax: {
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},"url": "/GetTable1","type": "POST",error: function(jqXHR,ajaxOptions,thrownError) {
console.log('error.jqXHR',jqXHR);
console.log('error.ajaxOptions',ajaxOptions);
console.log('error.thrownError',thrownError);
}
}
/* ... */
});
解决方法
代替使用Datatables::of()
,而尝试使用Datatables::eloquent()
,这可以使查询更快,尤其是在排序和过滤过程中,因为它实际上在查询过程中将其包括在SQL语句中,而不是在获得所有结果之后进行过滤
您可以在https://yajrabox.com/docs/laravel-datatables/master/engine-eloquent#facade
上引用更多内容