问题
i am trying to fetch record with order by query but situation is this that i have to use order by both on current table column and relationship table column in laravel . I tried this
$consignments = Consignment::where('delivery_run_id', $id)->whereIn('status', [
'In Warehouse',
'With On Forwarder',
'In Transit (Warehouse->Delivery)',
'Awaiting Pickup'
])->with(['consignment_run_sheet' => function ($query) {
$query->orderBy('run_sheet_id');
}])->orderBy('delivery_date', 'DESC')->get();
$deliveryRuns = DeliveryRun::all();
How I can achieve it?
回答1:
it will order just the relation items in this way. solution is use subquery or joins. useing Subquery is like this if assume the modal for consignment_run_sheet relation is ConsignmentRunSheet and the relation is belongsTo:
$consignments = Consignment::where('delivery_run_id', $id)->whereIn('status', [
'In Warehouse',
'With On Forwarder',
'In Transit (Warehouse->Delivery)',
'Awaiting Pickup'
])->with('consignment_run_sheet')
->orderBy(ConsignmentRunSheet::select('delivery_date')
->whereColumn('consignments.id', 'consignment_run_sheet.consignment_id'), 'DESC')
->get()
source: https://reinink.ca/articles/ordering-database-queries-by-relationship-columns-in-laravel
来源:https://stackoverflow.com/questions/62815518/how-to-use-order-by-query-both-with-current-table-column-and-relationship-table