SexyMF
SexyMF

Reputation: 11185

Laravel order by related table not working

I have this structure.

class Product extends Model{
    public function office()
    {
        return $this->belongsTo(Office::class,'office_id');
    }
}

I want to list products order by office.name.
this is the query

$res =  \App\Product::with(['office' => function($q){
        $q->orderBy('offices.name','asc');
    }])->get();

this is the output loop

    foreach($res as $key => $val){
        print "<br />user: ".$val->id.",  office: ".$val->office->id;
    }

this is the Product data: +----+--------+ | id | name | +----+--------+ | 1 | Life | | 2 | Cars | | 3 | Health | | 4 | House | +----+--------+

this is the data in Office +----+----------------+ | id | name | +----+----------------+ | 1 | First office | | 2 | working office | +----+----------------+

The order by is not affecting the result. same result, the order by like not existed.

Thanks

Upvotes: 0

Views: 500

Answers (1)

EddyTheDove
EddyTheDove

Reputation: 13259

In your code you are simply "ordering" the offices by name, which means if each product had many offices, it would sort the offices alphabetically.

To sort (OrderBY()) a collection, the column has to be an attribute of the collection object. One solution could be to Join your models. SOmething like this might help you.

$res = Product::with('office')
->join('offices', 'products.office_id', '=', 'offices.id')
->select('products.*', 'offices.name')
->orderBy('office.name')
->get();

Upvotes: 1

Related Questions