2

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
sheitan
  • 1,076
  • 12
  • 27
Vlad
  • 753
  • 2
  • 10
  • 26
  • 1
    Possible duplicate of [How to Use Order By for Multiple Columns in Laravel 4?](https://stackoverflow.com/questions/17006309/how-to-use-order-by-for-multiple-columns-in-laravel-4) – Tim Biegeleisen Apr 08 '19 at 05:32
  • Not the same thing. The problem is ordering by a nested relation by 2 levels. The link you specified is talking about ordering in a single table by 2 columns. – Vlad Apr 08 '19 at 05:34
  • Try to use trough relationship in your models https://laravel.com/docs/5.8/eloquent-relationships#has-many-through – mafortis Apr 08 '19 at 05:45
  • I need to access the "pivot" table `report_fied` for other table fields unique to that report so i cannot use the standard hasManyThrough. The relationships are made using belongsTo/hasMany. – Vlad Apr 08 '19 at 05:52

1 Answers1

3

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');
}
sheitan
  • 1,076
  • 12
  • 27