【问题标题】:Paginate API Laravel分页 API Laravel
【发布时间】:2016-12-03 18:45:40
【问题描述】:

我正在 Laravel 中构建一个 API,它对 Oracle 数据库执行以下操作:

从 table_a 中选择 *;

API 代码如下:

$response = [];
try {
    $response['status']     = 200;
    $response['message']    = 'ok';
    $response['parameters'] = [];
    $obj                    = DB::select("SELECT * FROM table_a");
    if (!empty($obj) && count($obj)) {
        $response['result'] = $obj;
    }
    else {
        $response['result'] = 'Requested data not found';
    }
}
catch (\Exception $e) {
    $response['status']     = 400;
    $response['message']    = 'ok';
    $response['parameters'] = [];
    $response['result']     = 'Sorry! bad request';
}

return response()->json($response);

table_a 有超过 3000 万条记录。我需要对 API 结果进行分页。我无法每次都计算表记录,因为执行计数查询需要几分钟。我怎样才能有效地得到它?

【问题讨论】:

    标签: oracle api laravel pagination


    【解决方案1】:

    您可以使用->paginate('n') 对结果进行分页。 Laravel 提供的 paginate 方法会自动根据用户正在查看的当前页面设置适当的限制和偏移量。默认情况下,当前页面由 HTTP 请求上的 ?page 查询字符串参数的值检测。

    在这种情况下,让我们指定我们希望每页显示15 个项目:

    namespace App\Http\Controllers;
    
    use DB;
    use App\Http\Controllers\Controller;
    
    class UserController extends Controller
    {
        /**
         * Show all of the users for the application.
         *
         * @return Response
         */
        public function index()
        {
            $users = DB::table('users')->paginate(15);
    
            return view('user.index', ['users' => $users]);
        }
    }
    

    【讨论】:

    • 我需要使用 Oracle 表,因此它将使用 Oracle 级别的存储过程。这不是一张普通的桌子。
    猜你喜欢
    • 2017-06-06
    • 1970-01-01
    • 2019-10-24
    • 1970-01-01
    • 2018-06-15
    • 2017-04-28
    • 2021-10-15
    • 1970-01-01
    • 2015-08-12
    相关资源
    最近更新 更多