2016-04-25 199 views
1

下....Laravel集合 - 結果訂購

控制器:

public function treatmentsList() 
    { 
     $treatments = Treatment::with('category')->where('status', 1)->orderBy('medical_name')->get(); 
     $groups = $treatments->groupBy('category.name'); 
     return view('pages.treatments.list', compact('groups')); 
    } 

查看:

<ul> 
    @foreach($groups as $category_name => $treatments) 
     <li> 
      <h4>{{ $category_name }}</h4> 
      <ul> 
       @foreach($treatments as $treatment) 
        <li> 
         <h5>{{ $treatment->medical_name }}</h5> 
        </li> 
       @endforeach 
      </ul> 
     </li> 
    @endforeach 
</ul> 

給我...

的治療方法中的分組類別和按字母順序,但類別不按字母順序。

- Category B 
Treatment A 
Treatment B 
Treatment C 

- Category A 
Treatment A 
Treatment B 

- Category C 
Treatment A 
Treatment B 
Treatment C 
Treatment D 

我怎樣才能得到按字母順序排列的治療和類別?

+0

您是否在groupBy函數調用後嘗試過使用' - > orderBy('category.name')'? –

+0

在groupBy給我之後添加' - > orderBy('category.name')':方法orderBy不存在。 – TickedTask

回答

1

您可以通過添加查詢約束條件預先加載查詢得到這樣的:

Treatment::with(['category' => function ($query) { 
    $query->orderBy('name'); 
}]) 
->where('status', 1) 
->orderBy('medical_name') 
->get(); 

嗨,

我不知道,如果這是你的意思......但它沒有工作...我仍然得到不按字母順序排列的類別。

public function treatmentsList() 
{ 
    $treatments = Treatment::with(['category' => function ($query) { 
     $query->orderBy('name'); 
    }]) 
     ->where('status', 1) 
     ->orderBy('medical_name') 
     ->get(); 
    $groups = $treatments->groupBy('category.name'); 
    return view('pages.treatments.listA', compact('groups')); 
} 

你說得對 - 我的錯。我認爲答案是加入查詢:

public function treatmentsList() 
{ 
    $treatments = Treatment::with('category') 
     ->select('treatment.*') 
     ->join('category', 'category.id', '=', 'treatment.category_id') 
     ->where('treatment.status', 1) 
     ->orderBy('category.name') 
     ->orderBy('treatment.medical_name') 
     ->get(); 
    $groups = $treatments->groupBy('category.name'); 
    return view('pages.treatments.listA', compact('groups')); 
} 

檢查上面例子中的表和字段的名稱。這應該工作。

+0

非常感謝你......我只是調整了表名,一切正常。 – TickedTask