如何在Laravel 4中使用多列的排序依据?

时间:2013-06-09 04:05:57

标签: php laravel laravel-4 eloquent laravel-query-builder

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

SELECT *
FROM mytable
ORDER BY
  coloumn1 DESC, coloumn2 ASC

我该怎么做?

5 个答案:

答案 0 :(得分:304)

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

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

生成以下查询:

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

答案 1 :(得分:15)

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

希望有所帮助:)

答案 2 :(得分:2)

像这样使用订单:

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

答案 3 :(得分:1)

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

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

答案 4 :(得分: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();