如何排序Laravel查询生成器的结果多列?

我想在Laravel Eloquent中使用orderBy()方法对Laravel 4中的多个列进行排序。查询将使用Eloquent像这样生成:

SELECT *
FROM mytable
ORDER BY
coloumn1 DESC, coloumn2 ASC

我该怎么做呢?

313699 次浏览

只要你需要调用orderBy()多次就可以了。例如:

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

产生以下查询:

SELECT * FROM `users` ORDER BY `name` DESC, `email` ASC

你可以按照@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();

希望能有所帮助。

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

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

像这样使用order by:

return User::orderBy('name', 'DESC')
->orderBy('surname', 'DESC')
->orderBy('email', 'DESC')
...
->get();
$this->data['user_posts'] = User_posts::with(['likes', 'comments' => function($query) { $query->orderBy('created_at', 'DESC'); }])->where('status', 1)->orderBy('created_at', 'DESC')->get();