【问题标题】:this current code needs pagination and sort, how i do?当前的代码需要分页和排序,我该怎么做?
【发布时间】:2022-01-03 12:49:07
【问题描述】:

我写了一段代码,检索用户列表并在检索到的数据上查找进度,但是我需要根据进度对asc进行排序,应该是分页,但我不知道该怎么做

既然用户多,有没有办法不用foreach就可以按查询分页排序?

下面是代码,是找进度的代码,用foreach不好,有没有更好的办法??也需要分页

$users = \App\Models\ChallengeUserPivot::where('challenge_id', $challenge_id)->get();

foreach($users as $user){
    $user_data = \App\Models\User::where('id', $user['user_id'])->first();
    $temp_progress = [];
    $temp_progress['total'] = 0;
    $temp_progress['doing'] = 0;
    foreach($challenge->ChallengeMissions as $key => $mission){
        $temp = ChallengeFunction::missionState($user_data, $mission);
        $temp_progress['total'] += (int)$temp['have_to_mission_count'];
        $temp_progress['doing'] += $temp['cert_count'];
    }
    $user['progress'] = ($temp_progress['doing'] / $temp_progress['total']) * 100;
}
    

【问题讨论】:

  • 到目前为止您尝试过什么?你被困在哪里了?您要对哪些部分进行分页? “不使用 foreach”是什么意思?

标签: php laravel sorting pagination


【解决方案1】:

您需要在查询中添加限制器和偏移量,并为每个分页增加偏移量。所以在这里你需要指定你想得到多少行(只是假设在这里插入限制):

\App\Models\ChallengeUserPivot::where('challenge_id', $challenge_id)->get(1000);

对于接下来的 1000 行,您需要添加 1000 行的偏移量。

所以第一行是 0-1000,接下来是 1000-2000,依此类推。这样您就不需要在一次调用中获取所有行。

【讨论】:

  • 为什么不直接使用paginate 方法?
  • 是的,只需使用分页功能(我现在可以看到它是 Laravel)。
猜你喜欢
  • 1970-01-01
  • 2016-11-13
  • 2020-05-24
  • 2015-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-15
  • 1970-01-01
相关资源
最近更新 更多