skip to Main Content

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

2

Answers


  1. 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

    Login or Signup to reply.
  2. try this:

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

    for more approaches take a look at this link.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search