我想使用Laravel Eloquent中的orderBy()
方法对Larave4中的多个列进行排序。查询将使用Eloquent生成,如下所示:
SELECT *
FROM mytable
ORDER BY
coloumn1 DESC, coloumn2 ASC
我该怎么做呢?
发布于 2013-06-09 12:19:38
只需根据需要多次调用orderBy()
即可。例如:
User::orderBy('name', 'DESC')
->orderBy('email', 'ASC')
->get();
生成以下查询:
SELECT * FROM `users` ORDER BY `name` DESC, `email` ASC
发布于 2018-03-29 17:07:15
这是我为我的基本存储库类想出的另一个dodge,我需要按任意数量的列进行排序:
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);
发布于 2020-07-19 14:59:21
按如下方式使用order by:
return User::orderBy('name', 'DESC')
->orderBy('surname', 'DESC')
->orderBy('email', 'DESC')
...
->get();
https://stackoverflow.com/questions/17006309
复制相似问题