I'm trying to paginate results (every 25 rows) using Select2 4.0, but I don't know how to achieve it. Does somebody know how to do it?

If the user reach the end of the 25 rows and if there is more rows I would like to load it and show it.

这是我的HTML模板

<div class="form-group">
    {!! Form::select('breed_id', $breeds, null, ['class' => 'form-control', 'id' =>'breed_id'] ) !!}
</div>

And here is the JavaScript for Select2.

$("#breed_id").select2({
    placeholder: 'Breed...',
    width: '350px',
    allowClear: true,
    ajax: {
        url: '',
        dataType: 'json',
        data: function(params) {
            return {
                term: params.term
            }
        },
        processResults: function (data, page) {
            return {
                results: data
            };
        },
        cache: true
    }
});

这是我控制器的代码

if ($request->ajax())
{
    $breeds = Breed::where('name', 'LIKE',  '%' . Input::get("term"). '%')->orderBy('name')->take(25)->get(['id',DB::raw('name as text')]);

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

另外,当我试着输入params.page时,它会显示"未定义".

推荐答案

Select2 supports pagination when using remote data through the pagination key that comes out of processResults.

For infinite scrolling, the pagination object is expected to have a more property which is a boolean (true or false). This will tell Select2 whether it should load more results when reaching the bottom, or if it has reached the end of the results.

{
  results: [array, of, results],
  pagination: {
    more: true
  }
}

In your case, you have the ability to shape your results. So you can actually change your JSON response to match the expected format, which means you won't even need to use processResults.

如果修改ajax.data函数以返回页码,则Select2可以将页码传递为page.

data: function(params) {
    return {
        term: params.term || "",
        page: params.page || 1
    }
},

然后你就可以使用Input::get('page')来获取页面.您可以使用(page - 1) * resultCount计算要跳过的结果总数,在您的例子中,resultCount25.这将允许您修改查询,将LIMITOFFSET组合起来,以获得所需的结果.

$page = Input::get('page');
$resultCount = 25;

$offset = ($page - 1) * $resultCount;

您可以使用以下查询生成LIMIT/OFFSET查询(基于this Stack Overflow question.

$breeds = Breed::where('name', 'LIKE',  '%' . Input::get("term"). '%')->orderBy('name')->skip($offset)->take($resultCount)->get(['id',DB::raw('name as text')]);

所以现在$breeds将只包含请求的结果.剩下要做的唯一一件事就是根据Select2的预期来调整响应.您可以通过判断结果总数并查看是否超出限制来确定是否有更多页面.

$count = Breed::count();
$endCount = $offset + $resultCount;
$morePages = $endCount > $count;

So now $morePages should be a boolean, which is exactly what Select2 is looking for in pagination.more. Now you just need to shape the response to match the format I mentioned earlier.

$results = array(
  "results" => $breeds,
  "pagination" => array(
    "more" => $morePages
  )
);

And then rendering that

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

Putting everything together, you get this for JavaScript

$("#breed_id").select2({
    placeholder: 'Breed...',
    width: '350px',
    allowClear: true,
    ajax: {
        url: '',
        dataType: 'json',
        data: function(params) {
            return {
                term: params.term || '',
                page: params.page || 1
            }
        },
        cache: true
    }
});

以下是你的控制器

if ($request->ajax())
{
    $page = Input::get('page');
    $resultCount = 25;

    $offset = ($page - 1) * $resultCount;

    $breeds = Breed::where('name', 'LIKE',  '%' . Input::get("term"). '%')->orderBy('name')->skip($offset)->take($resultCount)->get(['id',DB::raw('name as text')]);

    $count = Breed::count();
    $endCount = $offset + $resultCount;
    $morePages = $endCount > $count;

    $results = array(
      "results" => $breeds,
      "pagination" => array(
        "more" => $morePages
      )
    );

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

Laravel相关问答推荐

Laravel-如何按第三表关系对数据进行分类

如何通过 Eloquent 获取单个集合中每位教师的学生人数

在 laravel 项目中放置 css 文件的位置

Laravel & Docker:无法打开流或文件/var/www/html/storage/logs/laravel.log:无法打开流:权限被拒绝

Laravel 4,如何测试复选框是否被选中?

使用 vue-router 更改路由时中止所有 Axios 请求

laravel 5 - assets资源 list 中未定义 css 文件?

SQLSTATE [01000]:警告:1265 列的数据被截断(truncated)

Laravel Artisan CLI 安全地停止守护进程队列工作者

如何使用外部图像生成 html div 的 screenshot截图?

Laravel 动作未定义

Laravel Eloquent 在子查询中有两个WHERE NOT IN

如何在 Laravel 查询中使用多个 OR、AND 条件

Laravel 4 上传图片表单

Filesystem.php 中的 ErrorException

Laravel Eloquent ORM 复制

在 Laravel artisan 命令中使用详细

如何在 Laravel 中使用补丁请求?

Laravel 更新后用户模型错误(用户类包含 3 个抽象方法)

Laravel 5 Illuminate\Http\Request 的方法不允许静态调用