代码之家  ›  专栏  ›  技术社区  ›  Ashish

Laravel:反转分页查询的结果

  •  0
  • Ashish  · 技术社区  · 7 年前

    我使用的是Laravel 5.6,我想反转分页查询的结果。这就是我要做的:

    $chats = Chats::where('message_id', $message_id)->orderBy('id', 'DESC')->paginate(5);
    if(!empty($chats)) {
        $data['messages'] = $chats->reverse()->values();
        $data['status'] = 200;
        $data['create_user_id'] = Auth::id();
    }else{
        $data['error'] = "No chats available";
    }
    

    但是它从结果中删除了分页。假设我在表中有这10个值

    1, 2, 3, 4, 5, 6, 7, 8, 9, 10
    

    现在我想要 6, 7, 8, 9, 10 在第一页的结果和 1, 2, 3, 4, 5 在第二页的结果中,特别是按照这个顺序。

    我怎么得到这个?请帮忙!!!

    2 回复  |  直到 7 年前
        1
  •  3
  •   GTCrais    7 年前

    好,

    ->orderBy('id', 'DESC')
    

    在你的分页查询中,应该给你

    `10, 9, 8, 7, 6`
    

    然后把输出中的那些倒过来

    `6, 7, 8, 9, 10`
    

    代码示例:

    // $chats here are instance of LengthAwarePaginator
    // so we use ->items() to get the array of paginated objects
    $chats = Chats::orderBy('id', 'desc')->paginate(5);
    $data = [];
    
    if ($chats->count()) {
        $data['reverseModels'] = collect($chats->items())->reverse();
        $data['reverseIds'] = collect($chats->items())->reverse()->pluck('id');
    } else {
        $data['error'] = 'Error';
    }
    
        2
  •  0
  •   RoshJ    7 年前

    我有一个查看员工出勤率的功能,这里我是按降序日期对结果进行分页的。我得到的结果是正确的。

        public function viewAttendance($id){
            $q = Attendance::where('emp_id','=',$id)
               ->orderBy('date','desc')
               ->select('attendance.*')
               ->paginate(10);
            return $q;
        }