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
CodePudding user response:
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();
CodePudding user response:
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.