2016-10-27 78 views
0

案例二階hasManyThrough關係

項目
id | Name

戶型
id | Name | Project_id

類型
id | Name | House_type_id

房屋
id | Building_nr | Type_id

所有houses(/公寓)有relationshiptype(XL公寓,小戶型)。一類有relation與房屋types(別墅,獨立屋)和house typerelationproject

所以這裏使用了三個one-to-many relationships

我想order房屋的基礎上的建築物數量。

如何我目前從我的數據庫獲取數據:

$project = Project::whereSlug($slug)->with(array('brokers', 'houseTypes.types.houses' => function($query) { 
     $query->orderBy('bnr'); 
    }))->first(); 

但是這並不能導致最後的關係(房屋)被他們bnr(樓號)排序。

我如何將數據加載到我的觀點:

@foreach($project->houseTypes as $houseTypes) 
    @foreach($houseTypes->types as $types) 
     @foreach($types->houses->sortBy('bnr') as $house) 
      <tr class="table-row"> 
       <td>{{$house->bnr}}</td> 
       <td>{{$house->type->houseType->title}}</td> 
       <td>{{$house->type->rooms}}</td> 
       <td>&euro;{{$house->price}}</td> 
       <td>{{$house->living_surface}}m<sup>2</sup></td> 
       <td>{{$house->water}}m<sup>2</sup></td> 
       <td>{{$house->location}}</td> 
      </tr> 
     @endforeach 
    @endforeach 
@endforeach 

什麼是讓我期待的結果最有效的/最好的方法是什麼?

編輯:
現在我有另一種解決方案,使用JavaScript根據建築物編號(帶有行的表)對錶進行排序。出於興趣,使用正確的查詢仍然可以解決這個問題嗎?

回答

0

嘗試財產以後這樣

Houses::whereHas('project', function($q){ 
    $q->where('slug','like',$slug); 
})->with('/* All your relationships */')->orderBy('bnr');