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

16.2k views Asked by At

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!

11

There are 11 answers

1
prateekkathal On

The distinct is working.... When you make a join, it checks for distinct entries in all selected columns and here.. the column names you get after the join are also included in the join...

To run this please add select() to your builder instance and it should work :)

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

Let me know if this doesn't work for you :)

2
AddWeb Solution Pvt Ltd On

I found the problem at my code, that is I need to pass $column as second parameter into paginate($perPage, $columns, $pageName, $page). I got the solution from laravel git issue.

So my working code:

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

Need suggestion
What if, I hack the code for Builder.php to bypass passing the second parameter $column. I mean this is the good thing OR any batter option?

/**
 * Paginate the given query into a simple paginator.
 *
 * @param  int  $perPage
 * @param  array  $columns
 * @param  string  $pageName
 * @param  int|null  $page
 * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
 */
public function paginate($perPage = 15, $columns = null, $pageName = 'page', $page = null)
{

    //To solved paginator issue with distinct...
    if(is_null($columns) && strpos($this->toSql(), 'distinct') !== FALSE){
        $columns = $this->columns; 
        $columns = array_filter($columns, function($value) {
            return (is_string($value) && !empty($value));
        });
    }
    else {
        //If null $column, set with default one
        if(is_null($columns)){
            $columns = ['*'];
        }
    }

    $page = $page ?: Paginator::resolveCurrentPage($pageName);

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

    $results = $total ? $this->forPage($page, $perPage)->get($columns) : [];

    return new LengthAwarePaginator($results, $total, $perPage, $page, [
        'path' => Paginator::resolveCurrentPath(),
        'pageName' => $pageName,
    ]);
}
2
patricus On

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.*']);
0
Mohit Prajapati On

Use groupBy() instead of distinct(). I haven't tested but it will work. I was facing same issue in my query.

$author = Author::select('author_name')->groupBy('author_name')->paginate(15); 
0
Lundis On

While other answers explain the issue and workarounds well, doing a join to accomplish an existance check does not really make sense. Do a whereIn instead - this avoids the issue and makes it obvious at a glance what you are doing in the query. As per your example:

DB::table('myTable1 AS T1')
    ->whereIn('T1.id', fn(Builder $q) => $q->
        select('T2.id')->from('T2'))
    ->paginate(5);

You can add any where condition you might need to T2.

1
Azwar Salal On

use groupby with paginate to remove duplicacy

1
Govind Totla On

Pass the column name in distinct().

I have multiple tables joined and need distinct data. So listings work perfectly with distinct but the total records count during pagination was wrong and I landed on this thread. later, I was able to solve this by passing an argument in the distinct method.

DB::table('myTable1 AS T1')
    ->select('T1.*')
    ->join('myTable2 AS T2','T2.T1_id','=','T1.id')
    ->distinct(['T1.id'])
    ->paginate(5);
0
Burak Aşkın On

Disticnt with Laravel is malfunctioning. I solved this problem using groupBy.

0
Mishanki On

Pagination with multiple distinct.

composer require larahook/distinct-on-pagination

Usage

SomeModel::select(['*'])
    ->distinct(['field_a', 'field_b'])
    ->orderBy('field_a')
    ->orderBy('field_b')
    ->paginate($perPage)
0
tauseedzaman On

I had the same issue and I solved it by using ->groupby->paginate()

0
Gevorg Melkumyan On

If it is possible, you can change distinct() with groupBy().