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

SELECT *
FROM mytable
ORDER BY
  coloumn1 DESC, coloumn2 ASC

我该怎么做呢?


当前回答

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

其他回答

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

使用order by两次:

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

第二种方法是,

使用原始顺序:

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

还有一种方法是循环迭代,

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

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

$results = $query->get();

希望能有所帮助。

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

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

产生以下查询:

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

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

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);
$this->data['user_posts'] = User_posts::with(['likes', 'comments' => function($query) { $query->orderBy('created_at', 'DESC'); }])->where('status', 1)->orderBy('created_at', 'DESC')->get();

像这样使用order by:

return User::orderBy('name', 'DESC')
    ->orderBy('surname', 'DESC')
    ->orderBy('email', 'DESC')
    ...
    ->get();