2016-10-27 53 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');