Answers:
只需orderBy()
根据需要调用多次。例如:
User::orderBy('name', 'DESC')
->orderBy('email', 'ASC')
->get();
产生以下查询:
SELECT * FROM `users` ORDER BY `name` DESC, `email` ASC
User::orderBy(array('name'=>'desc', 'email'=>'asc'))
$user->orders = array(array('column' => 'name', 'direction' => 'desc'), array('column' => 'email', 'direction' => 'asc'));
get
或first
),只需对其进行调用orderBy
。否则,不。
您可以按照@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);
User::orderBy('name', 'DESC') ->orderBy('email', 'ASC') ->get();