Home > OS >  Laravel: sort query results based on field of nested relationship
Laravel: sort query results based on field of nested relationship

Time:09-25

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.

CodePudding user response:

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();

CodePudding user response:

You can define new relations in User and Company models.

User

public function orders()
{
    return $this->hasMany(Order::class);
}

Company

public function users()
{
    return $this->hasMany(User::class);
}

Now you can fetch companies that are in asc order and with the use of relation, you can fetch users and orders. So the ORM like be,

$companies = Company::with(['users.orders'])->orderBy('title', 'ASC')->get();

So these are the company-wise orders. You can use this too.

  • Related