sanu
sanu

Reputation: 1068

Laravel Order by in one to many relation with second table column

Hi i have tables with one to many relation

sectors

id
name
position

seat_plans

id
name
sector_id

I just want to select all seat plans order by sectors.position. I tried

 $seat_plans = SeatPlan::with(['sector' => function($q){
                                        $q->orderBy('position');
                                        }
                                    ])->get();

but it is not working. when i check The SQL it is generating query like

select * from seat_plans

can anybody please tell me how to do this?

Upvotes: 0

Views: 551

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521209

I don't think you need a custom function for your use case. Instead try this:

$users = DB::table('seat_plans')
            ->join('sectors', 'seat_plans.sector_id, '=', 'sectors.id')
            ->select('seat_plans.*')
            ->orderBy('sectors.position')
            ->get();

Upvotes: 1

Related Questions