問題描述
我正在嘗試在 laravel 5.2 中使用 distinct()
和 pagination()
流利,結果正確,但分頁仍然存在相同(就像沒有應用不同).
I'm trying to use distinct()
with pagination()
in laravel 5.2 with fluent and it's given result proper but pagination remain same(Like without apply distinct).
我已經使用我的代碼查看并測試了以下答案
- laravel 5 - 使用不同的分頁對 total() 查詢/a>
- 分頁 &與眾不同
- 使用 distinct 時查詢生成器分頁方法計數錯誤
我的代碼類似于:
DB::table('myTable1 AS T1')
->select('T1.*')
->join('myTable2 AS T2','T2.T1_id','=','T1.id')
->distinct()
->paginate(5);
示例
- 我得到了三個記錄(即 POST1、POST2、POST3 和 POST1)的結果,所以我應用了 distinct()
.
- 現在我的結果是 POST1、POST2 和 POST3 但分頁仍然顯示為 4 條記錄(作為應用 distinct()
之前的結果).
EXAMPLE
- I have result with three records(i.e. POST1, POST2, POST3 and POST1) so I apply distinct()
.
- Now my result is POST1, POST2 and POST3 but pagination still display like 4 records(As result before applied distinct()
).
任何建議將不勝感激!
推薦答案
Laravel 和在分頁中使用 distinct 似乎存在一些持續的問題.
There seems to be some ongoing issues with Laravel and using distinct with pagination.
在這種情況下,當分頁確定記錄總數時,它會忽略您在 select()
子句中指定的字段.由于它忽略了您的列,因此也忽略了不同的功能.因此,計數查詢變為 select count(*) as aggregate from ...
In this case, when pagination is determining the total number of records, it is ignoring the fields you have specified in your select()
clause. Since it ignores your columns, the distinct functionality is ignored as well. So, the count query becomes select count(*) as aggregate from ...
要解決此問題,您需要將您的列的分頁功能告知.傳遞您的列數組以選擇作為第二個參數,它會將它們計入總計數.所以,如果你這樣做:
To resolve the issue, you need to tell the paginate function about your columns. Pass your array of columns to select as the second parameter, and it will take them into account for the total count. So, if you do:
/*DB::stuff*/->paginate(5, ['T1.*']);
這將運行計數查詢:
select count(distinct T1.*) as aggregate from
因此,您的查詢應如下所示:
So, your query should look like:
DB::table('myTable1 AS T1')
->select('T1.*')
->join('myTable2 AS T2','T2.T1_id','=','T1.id')
->distinct()
->paginate(5, ['T1.*']);
這篇關于在laravel 5.2中使用分頁()的distinct()不起作用的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!