Home > Back-end >  How to filter by relation column Laravel
How to filter by relation column Laravel

Time:03-23

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

CodePudding user response:

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');

CodePudding user response:

request {{host}}/admin/showcases?filterBy=companies:name it order by relation column companies

if simple {{host}}/admin/showcases?filterBy=name it will be only orderBy("name")

->when(str_contains($filterBy, ':'),
                function (Builder $query) use ($filterBy, $order, $columns) {
                    $table = explode(':', $filterBy)[0];
                    $key = Str::singular($table) . "_id";
                    $column = explode(':', $filterBy)[1];
                    $selfTable = $this->getTable();
                    $query->leftJoin($table, "$selfTable.$key", "$table.id")
                            ->when($columns !== ['*'],
                                    function ($query) use ($columns, $selfTable) {
                                        $columns = array_map(function ($column) use ($selfTable) {
                                            return "$selfTable.$column";
                                        }, $columns);
                                        $query->select($columns);
                                    },
                                    fn($query) => $query->select(["$selfTable.*"]))
                            ->orderBy("$table.$column", $order);
                },
                function ($query) use ($filterBy, $order) {
                    $query->orderBy($filterBy, $order);
                })
  • Related