Laravel在查询中添加数字行

时间:2018-09-23 16:12:13

标签: mysql laravel eloquent

我正在获取用户及其积分,我按积分对他们进行排序并分页。现在,我想添加一个数字行作为结果,因此第一个放置的用户将具有num。第1行,第2行,依此类推。

目前我有这个:

$scores=DB::table('scores')->join('users', 'users.id', '=', 'scores.user_id') 
                           ->join('sports', 'sports.id', '=', 'scores.sport_id')
                           ->join('leagues', 'leagues.id', '=', 'scores.league_id')
                           ->select('users.username','points','sports.sportName','leagues.leagueName')
                           ->orderBy($request->sort, $request->direction)->paginate(4);
return json_encode($scores);

编辑:我正在使用vue-tables 2,因此在API返回表自动创建之后,我无法使用foreach打印行号。预期结果将是:

Num.    Username    Points
1       test2       55
2       test5       42
3       test1       25
4       test4       5

JSON结果:

{"data":[
    {"num":"1","username":"test2","points":22},
    {"num":"2","username":"test1","points":13},
    {"num":"3","username":"test4","points":12}
]

}

1 个答案:

答案 0 :(得分:1)

使用foreach()循环:

$num = ($scores->currentPage() - 1) * $scores->perPage() + 1;

foreach($scores as $score) {
    $score->num = $num++;
}