How to Use Order By for Multiple Columns in Laravel 4?

后端 未结 4 1877
花落未央
花落未央 2020-11-27 05:11

I want to sort multiple columns in Laravel 4 by using the method orderBy() in Laravel Eloquent. The query will be generated using Eloquent like this:

         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 05:21

    You can do as @rmobis has specified in his answer, [Adding something more into it]

    Using order by twice:

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

    and the second way to do it is,

    Using raw order by:

    MyTable::orderByRaw("coloumn1 DESC, coloumn2 ASC");
        ->get();
    

    Both will produce same query as follow,

    SELECT * FROM `my_tables` ORDER BY `coloumn1` DESC, `coloumn2` ASC
    

    As @rmobis specified in comment of first answer you can pass like an array to order by column like this,

    $myTable->orders = array(
        array('column' => 'coloumn1', 'direction' => 'desc'), 
        array('column' => 'coloumn2', 'direction' => 'asc')
    );
    

    one more way to do it is iterate in loop,

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

    Hope it helps :)

提交回复
热议问题