2017-08-24 85 views
0

這裏整理一組是我的查詢:Laravel雄辯的元素

return App\AftermarketParts::where('alt', 'LIKE', "%$search%") 
     ->orderBy('alt',"$direction") 
     ->with('aftermarket_parts_type') 
     ->get() 
     ->groupBy('aftermarket_parts_type_id'); 

這裏設置我的數據:

(16) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}] 
0:alt:(...) 
    created_at:(...) 
    deleted_at:(...) 
    id:(...) 
    image:(...) 
    image_height:(...) 
    image_width:(...) 
    link:(...) 
    tires_and_rims_type:Object 
    created_at:(...) 
    deleted_at:(...) 
    description:(...) 
    id:(...) 
    name:(...) 
    updated_at:(...) 
1:{…} 
2:{…} 

我試圖通過對結果進行排序當然這不起作用。

return App\AftermarketParts::where('alt', 'LIKE', "%$search%") 
      ->orderBy('alt',"$direction") 
      ->orderBy('name',"$name_direction") 
      ->with('aftermarket_parts_type') 
      ->get() 
      ->groupBy('aftermarket_parts_type_id'); 

我也曾嘗試:

return DB::table('aftermarket_parts') 
    ->join('aftermarket_parts_categories','aftermarket_parts_categories.id','=','aftermarket_parts.aftermarket_parts_type_id') 
    ->select(DB::raw(
     'aftermarket_parts.id, 
     aftermarket_parts.link, 
     aftermarket_parts.image, 
     aftermarket_parts.webpage_screen_shot, 
     aftermarket_parts.alt, 
     aftermarket_parts.image_width, 
     aftermarket_parts.image_height, 
     aftermarket_parts.aftermarket_parts_type_id, 
     aftermarket_parts.deleted_at, 
     aftermarket_parts.created_at, 
     aftermarket_parts.updated_at')) 
    ->groupBy('name') 
    ->orderBy('aftermarket_parts.alt', "$direction") 
    ->orderBy('name', "$groupDirection") 
    ->get(); 

返回數據集:

data:Array(80) 
    0: 
    aftermarket_parts_type_id:(...) 
    alt:(...) 
    created_at:(...) 
    deleted_at:(...) 
    id:(...) 
    image:(...) 
    image_height:(...) 
    image_width:(...) 
    link:(...) 
    updated_at:(...) 
    webpage_screen_shot:(...) 

即使它返回訂單正確它破壞對象的數組中的格式,我需要他們我想知道是否有辦法通過雄辯的呼叫做到這一點,或者我應該只使用一個PHP排序數組?想法?先謝謝你。

回答

0

最後一個前面的解決方案顛倒了數組的順序,這個使用冒泡排序來排序數組。

function bubbleSort($Array) { 
    $lastPos = count($Array); 
    for($lastPos -1; $lastPos >= 1; $lastPos--) { 
     for($i = 1; $i <= $lastPos -1; $i++) { 
      if($Array[$i][0]->aftermarket_parts_type->name > $Array[$i+1][0]->aftermarket_parts_type->name) { 
       $temp = $Array[$i]; 
       $Array[$i] = $Array[$i+1]; 
       $Array[$i+1] = $temp; 
      } 
     } 
    } 
    return $Array; 
} 
0

我只能想到的解決方案是在不使用雄辯或sql的情況下顛倒數組順序。它很簡單,它的作品。

$AftermarketParts = App\AftermarketParts::where([ 
      ['alt', 'LIKE', "%$search%"] 
     ]) 
     ->orderBy('alt',"$direction") 
     ->with('aftermarket_parts_type') 
     ->get() 
     ->groupBy('aftermarket_parts_type_id'); 

    $temp = []; 
    $j = 0; 
    for ($i=count($AftermarketParts); $i > 0; $i--) { 
     $temp[$j] = $AftermarketParts[$i]; 
     $j++; 
    } 
    return $temp;