Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

php - distinct() with pagination() in laravel 5.2 not working

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

I have already reviewed and tested below answers with mine code
- laravel 5 - paginate total() of a query with distinct
- Paginate & Distinct
- Query Builder paginate method count number wrong when using distinct

My code is something like:

DB::table('myTable1 AS T1')
->select('T1.*')
->join('myTable2 AS T2','T2.T1_id','=','T1.id')
->distinct()
->paginate(5);

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()).

Any suggestion would be appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There seems to be some ongoing issues with Laravel and using distinct with pagination.

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.*']);

This will run the count query of:

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.*']);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...