Search code examples
phplaravelsql-order-byrelationship

How to filter by relation column Laravel


How to filter by relation column

tried this
        ->whereHas('customer',function ($query) use ($order){
            $query->orderBy('first_name', $order);
        })
and this
        ->with(['customer' => function ($query) use ($order) {
            $query->orderBy('first_name', $order);
        }])

Both did not work


Solution

  • with() are using eager loading, which turns this into two queries.

    You need to use join() instead of with()

    $orders = Order
            ::join('customers', 'order.customer_id', '=', 'customers.id')
            ->orderBy('customers.first_name')
            ->get();
    

    OR

    You may use sortBy() or sortByDesc() methods of Collection.

    For example:

    $orders = Order
            ::with('customer')
            ->get()
            ->sortBy('customer.first_name');