Laravel排序查询结果

时间:2018-01-28 13:24:43

标签: php laravel sorting

我需要在使用get之后对查询进行排序,因为我将数据附加到查询的某些对象,如此

  $the_result = myTable::where(..)->paginate();
  foreach( $the_result as $result)
  {
       if( some code )
       { 
           // append the pending_postion  to $result
           $result->pending_postion = $a_number; //number ex = 5 
       }
  }

那么如何通过pending_postion对$ the_result进行排序?

我试过

$the_result ->sortBy('pending_postion');
collect($the_result )->sortBy('pending_postion');
return $the_result ;

输出

{
"current_page": 1,
"data": [
    {
        "id": 226,
        "property_id": 40, 
        "is_pending": false
    },
    {
        "id": 227,
        "property_id": 40, 
        "is_pending": true,
        "pending_postion": 6
    },
    {
        "id": 228,
        "property_id": 40, 
        "is_pending": true,
        "pending_postion": 4
    },
     {
        "id": 229,
        "property_id": 40, 
        "is_pending": false
    },

] }

2 个答案:

答案 0 :(得分:0)

如您所见,使用Collection方法后,您获得了get。所以你可以使用 sort method for collection

foreach( $the_result as $result)
{
   if( some code )
   { 
       // append the pending_postion  to $result
       $result->pending_postion = $a_number; //number ex = 5 
   }
}
$the_result->sortBy('pending_postion');

答案 1 :(得分:0)

添加sortBy()方法,例如$the_result = myTable::where(..)->get()->sortBy('pending_postion');

{{1}}