A
A
Alexander Shapoval2016-08-29 09:28:10
Laravel
Alexander Shapoval, 2016-08-29 09:28:10

How to add record sequence number field in SQL query?

There is a request:

$users = DB::table('users')
->whereBetween('votes', [20, 100])
->orderBy('votes', 'desc')
->paginate(10);

It returns:
4
7
1
5
15
and id.
How to add a boolean field 'rank' and get:
1 - 4
2 - 7
3 - 1
4 - 5
5 - 15
At the same time, when entering the second page, you need to display 'rank' from 10

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Aksentiev, 2016-08-29
@Sanasol

$i = ($page_num*10)-1;

foreach(){
$i++;
echo $i;
}

Well, or https://laravel.com/docs/5.3/pagination#paginator-...

B
boodda, 2016-08-29
@boodda

With such a request, it will return all columns to you. Therefore, if you have an ID field in your table, then you can output it as

foreach($users as $user){
    echo $user->id;
}

or in template
@foreach($users as $user)
    {{ $user->id }}
@endforeach

if you only want 2 columns from query then add select like this
$users = DB::table('users')
->select('id', 'rank')
->whereBetween('votes', [20, 100])
->orderBy('votes', 'desc')
->paginate(10);

R
Roman, 2019-06-01
@RomanTrakhtenberg

$i = 1;
    if ($data->currentPage() > 1){
        $i = (30 * ($data->currentPage()-1))+1;
    }

The number specified in ->paginate(30).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question