Search code examples
laravellaravel-8relationshiplaravel-9

How to sort based on a column with a one to many relationship


What I'm trying to do is this:

I have two tables with One to Many relationship

sectors

id
name
position
set_plan_id

seat_plans

id
name
order

I want to sort all sectors based on the order field present in seat_plans (which is of type numeric, so sort in ascending order).

I tried this code but I get unsorted sectors.

$sectors= Sector::whereHas('seat_plan', function ($query) {                                         
            $query->orderBy('order'); 
        })->get();

Can anyone kindly help me? thank you all


Solution

  • You have the option to do a join with the table like so:

    $sectors = Sector::join('seat_plans', 'seat_plans.id', '=', 'sectors.seat_plan_id')
        ->orderBy('seat_plans.order')
        ->select('sectors.*')
        ->get();
    

    Or make use of the aggregate method like shown below:

    $sectors = Sector::withAggregate('seat_plan', 'order')
       ->orderBy('seat_plan_order')
       ->get();
    

    reference: https://laravel.com/api/9.x/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.html#method_withAggregate