singlequote / Laravel-datatables

This repo contains a Datatable that can render a filterable and sortable table. It aims to be very lightweight and easy to use. It has support for retrieving data asynchronously, pagination and recursive searching in relations.
https://singlequote.github.io/Laravel-datatables/
MIT License
18 stars 6 forks source link

When using the new filters how would you modify query based on Dot notation #49

Closed happymacarts closed 2 years ago

happymacarts commented 2 years ago

for example my model has a relationship "info" if i wanted to modify the filter "where info.archive is null" what would that look like

public function filter(): array
{
  $filter = [
      [
        'name' => "Include  Archive",
        "id" => 1
      ], [
        'name' => "Without Archive",
        "id" => 2
      ]
  ];
  return [
    Dropdown::make('filter')
      ->label("Include Archive")
      ->data($filter),
  ];
}

public function query($query)
    {
        if ($this->getFilter('filter') && (int) $this->getFilter('filter') === 2) {
            return $query
                ->whereNull('info.archive') // <- how should i do this?
                ->with('user', 'status', 'info')
                ->withTrashed(); 
        }
        return $query->whereNotNull('info.archive')
            ->with('user', 'status', 'info')
            ->withTrashed();
    }
wimurk commented 2 years ago

Hi @happymacarts

I think you are trying to do a query on a relation? You can use the whereHas for that.

Check whereHas

public function query($query)
    {
        if ($this->getFilter('filter') && (int) $this->getFilter('filter') === 2) {
            return $query->whereHas('info', function($query){
                    $query->whereNull('archive');
                })->with('user', 'status', 'info')
                ->withTrashed(); 
        }
        return $query->whereDoesntHave('info', function($query){
                    $query->whereNull('archive');
                })
            ->with('user', 'status', 'info')
            ->withTrashed();
    }
happymacarts commented 2 years ago

exactly what I needed thx