【问题标题】:laravel paginate when use select case and parameter binding使用选择案例和参数绑定时的laravel分页
【发布时间】:2018-03-28 21:51:56
【问题描述】:

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);

这将获得 count 并且我们知道这将删除所有选择部分并将其替换为 count(*) 作为聚合,因此如果我在此查询构建器上使用 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();

对于这种情况,我知道这是错误的,但现在它有效!

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

【问题讨论】:

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


    【解决方案1】:

    你可以试试这个:

    这样写你的原始查询:

    DB::select('RAW_QUERY');
    

    它会返回一个数组。您可以使用 LengthAwarePaginator 对数组进行分页,如下所示:

    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()));
    }
    

    【讨论】:

      猜你喜欢
      • 2020-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-27
      • 2023-03-17
      相关资源
      最近更新 更多