jeudi 27 octobre 2016

Order second hasManyThrough relationship

Case

Projects
id | Name

House types
id | Name | Project_id

Types
id | Name | House_type_id

Houses
id | Building_nr | Type_id

All the houses (/apartments) have a relationship with type (XL apartment, small apartment). A type has a relation with house types (villa, detached house) and a house type has a relation with a project.

So three one-to-many relationships are being used here.

I want to order the houses based on the building numbers.

How I am currently fetching the data from my database:

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

But this doesn't result in the last relationship (houses) being ordered by their bnr(building number).

How I load the data into my view:

@foreach($project->houseTypes as $houseTypes)
    @foreach($houseTypes->types as $types)
        @foreach($types->houses->sortBy('bnr') as $house)
            <tr class="table-row">
                <td></td>
                <td></td>
                <td></td>
                <td>&euro;</td>
                <td>m<sup>2</sup></td>
                <td>m<sup>2</sup></td>
                <td></td>
            </tr>
        @endforeach
    @endforeach
@endforeach

What is the most efficient/best way to get the result I am looking for?

Edit:
For now I have another solution to use javascript for sorting the table based on the building number (table with rows). Out of interest, is the case still solvable using correct queries?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire