How to Use Order By for Multiple Columns in Laravel 4?

后端 未结 4 1907
花落未央
花落未央 2020-11-27 05:11

I want to sort multiple columns in Laravel 4 by using the method orderBy() in Laravel Eloquent. The query will be generated using Eloquent like this:

         


        
4条回答
  •  星月不相逢
    2020-11-27 05:15

    Here's another dodge that I came up with for my base repository class where I needed to order by an arbitrary number of columns:

    public function findAll(array $where = [], array $with = [], array $orderBy = [], int $limit = 10)
    {
        $result = $this->model->with($with);
        $dataSet = $result->where($where)
            // Conditionally use $orderBy if not empty
            ->when(!empty($orderBy), function ($query) use ($orderBy) {
                // Break $orderBy into pairs
                $pairs = array_chunk($orderBy, 2);
                // Iterate over the pairs
                foreach ($pairs as $pair) {
                    // Use the 'splat' to turn the pair into two arguments
                    $query->orderBy(...$pair);
                }
            })
            ->paginate($limit)
            ->appends(Input::except('page'));
    
        return $dataSet;
    }
    

    Now, you can make your call like this:

    $allUsers = $userRepository->findAll([], [], ['name', 'DESC', 'email', 'ASC'], 100);
    

提交回复
热议问题