Search code examples
laraveleloquentlaravel-query-builderlaravel-novaeloquent-relationship

Laravel: sort query results based on field of nested relationship


I have two models with relations as defined below

Order

public function owner()
{
    return $this->belongsTo(User::class, 'owner_id');
}

User

public function company(){
    return $this->belongsTo(Company::class, 'company_id');
}

company table have 'title' field. what I want is to get all the orders sorted/order by company title. I've tried different solution but nothing seems to work. Any help or hint would be appreciated.

Recent solution that I tried is

$query = OrderModel::whereHas('owner', function($q) use ($request){
             // $q->orderBy('owner');
             $q->whereHas('company',function ($q2) use ($request){
                 $q2->orderBy('title',$request->get('orderByDirection') ?? 'asc');
             });
         });

but I am not getting user and company relation in query results. also the result remains same for 'ASC' and 'DESC' order.


Solution

  • You could sort the query after adding join like:

    return Order::join('users', 'users.id', '=', 'owner_id')
            ->join('companies', 'companies.id', '=', 'users.company_id')
            ->orderBy('companies.title')
            ->select('orders.*')
            ->get();