Vlad
Vlad

Reputation: 792

How to order by column in nested 2 level relationship in Laravel?

I have 3 tables: reports, fields and report_fields which is a pivot between the other 2. What i need to do is order report_field.field by the position column in the field table.

I tried ordering in the relation in the Models or when using with but I may be doing it wrong. ex:

$query = Report::with([ 'reportFields.field' => function ($q) {
    $q->orderBy('position', 'asc');
    //$q->orderByRaw("fields.position DESC");
},

Can someone give a basic example of ordering a 2 level nested relationship?

Edit: I do not need to order by any column in the base table but the list of entries in the pivot table by an column in the second table.

Edit2:

To give an example how the output should be ordered:

Report
    ReportField
        Field.position = 1
    ReportField
        Field.position = 2
    ReportField
        Field.position = 3

Upvotes: 2

Views: 2973

Answers (1)

sheitan
sheitan

Reputation: 1156

You can add your needed ordering on the relation of the first table reports:

public function reportFields()
{
    return $this->hasMany(ReportFields::class)
        ->select('report_fields.*')
        ->join('fields', 'report_fields.field_id', 'fields.id')
        ->orderBy('fields.position', 'asc');
}

Upvotes: 3

Related Questions