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(*)作为聚合,所以如果我在此查询构建器上使用setBindings并传递[‘my-keyword’,’my-keyword’]对此聚合的查询将更改为:
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),Paginator::resolveCurrentPage(),array('path' => Paginator::resolveCurrentPath())); }