首页 > 解决方案 > Laravel Yajra 数据表原始 SQL

问题描述

使用 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);
        }
    }
    /* ... */
});

标签: laraveldatatableyajra-datatable

解决方案


而不是使用Datatables::of(),而是尝试Datatables::eloquent(),这可以使您的查询更快,尤其是在排序和过滤期间,因为它实际上在查询期间将其包含在 SQL 语句中,而不是在获得所有结果后对其进行过滤。

您可以参考https://yajrabox.com/docs/laravel-datatables/master/engine-eloquent#facade


推荐阅读