285

我想使用 Laravel Eloquent 中的方法orderBy()对 Laravel 4 中的多个列进行排序。查询将使用 Eloquent 生成,如下所示:

SELECT *
FROM mytable
ORDER BY
  coloumn1 DESC, coloumn2 ASC

我怎样才能做到这一点?

4

5 回答 5

476

orderBy()只需根据需要多次调用。例如:

User::orderBy('name', 'DESC')
    ->orderBy('email', 'ASC')
    ->get();

产生以下查询:

SELECT * FROM `users` ORDER BY `name` DESC, `email` ASC
于 2013-06-09T04:19:38.497 回答
53

你可以按照@rmobis 在他的回答中指定的那样做,[在其中添加更多内容]

使用order by两次:

MyTable::orderBy('coloumn1', 'DESC')
    ->orderBy('coloumn2', 'ASC')
    ->get();

第二种方法是,

使用raw order by

MyTable::orderByRaw("coloumn1 DESC, coloumn2 ASC");
    ->get();

两者都会产生如下相同的查询,

SELECT * FROM `my_tables` ORDER BY `coloumn1` DESC, `coloumn2` ASC

正如@rmobis 在第一个答案的评论中指定的那样,您可以像数组一样传递这样的按列排序

$myTable->orders = array(
    array('column' => 'coloumn1', 'direction' => 'desc'), 
    array('column' => 'coloumn2', 'direction' => 'asc')
);

另一种方法是iterate循环,

$query = DB::table('my_tables');

foreach ($request->get('order_by_columns') as $column => $direction) {
    $query->orderBy($column, $direction);
}

$results = $query->get();

希望能帮助到你 :)

于 2017-04-25T06:27:40.810 回答
4

这是我为我的基础存储库类提出的另一个闪避方法,我需要按任意数量的列进行排序:

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;
}

现在,您可以像这样拨打电话:

$allUsers = $userRepository->findAll([], [], ['name', 'DESC', 'email', 'ASC'], 100);
于 2018-03-29T09:07:14.530 回答
3

像这样使用 order by:

return User::orderBy('name', 'DESC')
    ->orderBy('surname', 'DESC')
    ->orderBy('email', 'DESC')
    ...
    ->get();
于 2020-07-19T06:59:21.137 回答
0
$this->data['user_posts'] = User_posts::with(['likes', 'comments' => function($query) { $query->orderBy('created_at', 'DESC'); }])->where('status', 1)->orderBy('created_at', 'DESC')->get();
于 2021-05-08T04:45:42.663 回答