简体   繁体   中英

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

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM