php - laravel 在使用选择大小写和参数绑定(bind)时分页

标签 php laravel laravel-query-builder laravel-paginate

Laravel 版本:5.5

PHP 版本:7

你好,我想执行这个查询:

select (case 
   when(title like 'my-keyword') then 1
   when(description like 'my-keyword') then 2
   ) as ordering from products where id > 10;

当我通过查询构建器执行此操作时:

$products = DB::table('products')->select(DB::raw('(case 
   when(title like '?') then 1
   when(description like '?') then 2
   ) as ordering'))->where('id', '>', 10)->setBinding(['my-keyword', 'my-keyword'])->paginage(10);

这将得到计数,正如我们所知,这将删除所有选择部分并将其替换为计数 (*) 作为聚合,因此如果我在此查询构建器上使用 setBindings 并传递 ['my-keyword', 'my-此聚合查询的关键字'] 将更改为:

select count(*) as aggregate from products where id > my-keyword;

因此,这将导致在此查询和其他类似查询中使用分页的问题!

为了解决这个问题,我在 /..../Query/Builder.php 中更改了一些代码:

$total = $this->getCountForPagination($columns);

为此:

$all = $this->get();
$total = $all->count();

对于这种情况,我知道这是错误的,但现在它起作用了!

我应该怎么做才能正确解决这个问题?!

最佳答案

你可以试试这个:

像这样写你的原始查询:

DB::select('RAW_QUERY');

It would return an array. You can use LengthAwarePaginator to paginate the array like so:

use Illuminate\Pagination\LengthAwarePaginator;


$this->paginateArray($array, $perPage); 

public function paginateArray($items, $perPage)
{
    $pageStart = \Request::get('page', 1);
    $offSet = ($pageStart * $perPage) - $perPage;
    $itemsForCurrentPage = array_slice($items, $offSet, $perPage, true);

    return new LengthAwarePaginator($itemsForCurrentPage, count($items), $perPage, Paginator::resolveCurrentPage(), array('path' => Paginator::resolveCurrentPath()));
}

关于php - laravel 在使用选择大小写和参数绑定(bind)时分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46786178/

相关文章:

php - 使用 Laravel Query Builder 进行复杂的 MySQL 内连接查询

mysql - 在 Laravel 的列中使用连接和逗号分隔值执行查询

php - 项目外的 Laravel 文件系统

php - 到底什么是 baseUrl

php - 如何让 Eloquent 将子集合推送到其父集合中?

php - Laravel 删除 X 记录(如果有重复项)的有效方法

php - wp-config.php 文件中的 WordPress WP_CACHE_KEY_SALT 值错误

php - 在 Android 上向 PHP/MySQL 后端发送和检索(可能是大量)数据的最佳方式是什么?

php - 如何让我的 SQL 查询搜索句子中的几个单词,即使它们不相互跟随

php - 如何将SQS延迟时间增加到900秒以上