How to use order by query both with current table column and relationship table column in laravel?

笑着哭i 提交于 2021-02-11 14:45:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!